<?php
namespace Admin\Controller;
use Admin\Logic\StoreLogic;
use Think\Page;
use Think\Page2;
use WXAPI\Controller\BaseController as base;
use WXAPI\Controller\PayController;

class FinanceController extends BaseController {
	public $begin;
	public $end;
	public $z;
    /*
     * 初始化操作  
     */
    public function _initialize() {
       parent::_initialize();
		$timegap = I('timegap');

		$timegap = str_replace('+',' ',$timegap);
		//echo $timegap;
		if($timegap){
			$gap = explode(' - ', $timegap);
			$begin = $gap[0];
			$end = $gap[1];
		}else{
			$lastweek = date('Y-m-d H:i',strtotime("-3 day"));
			$begin = I('begin',$lastweek);
			$end =  I('end',date('Y-m-d H:i'));
		}
		$this->begin = strtotime($begin);
		$this->end = strtotime($end);//+86399;
		$this->assign('timegap',date('Y-m-d H:i',$this->begin).' - '.date('Y-m-d H:i',$this->end));
		$this->z = !empty(\session('fenbu_id')) ? 'z' : '';
    }

     public function pda_piliang(){
		 $action=I('action');$datas=I('datas');
		 $pda_open=tpCache("basic")['pda_open'];
		if(!empty($action) && !empty($datas)){
			if($pda_open==0){
				exit;
			}
			$datas=\explode(',',$datas);
			$myorders='';
			$order_ids = '';
			foreach($datas as $v){
				$os=\explode('|',$v);
				$order_id=$os[0];
				$store_id=$os[1];
				
				//$order_list=M("order_goods")->field('goods_id,goods_num')->where('order_id='.$order_id)->select();//更新产品销量
                $order_goods = M('order_goods')->where(array('order_id' => $order_id))->select();//订单商品列表
					foreach($order_goods as $vv){
						M('goods')->where('goods_id='.$vv['goods_id'])->setInc('sales_sum',(int)$vv['goods_num']);
					}
					


					//溢价状态
					M("order_yijia")->where('order_id='.$order_id)->setField('yijia_status','1');
				
				//开始结算 
                $list = M('order')->where('order_id='.$order_id.' and order_status in (1,2)')->find();
                $order_statis = M('order_statis')->where(['order_sn'=>$list['order_sn']])->find();
                if($order_statis){
                    continue;
                } // 没有数据直接跳出
					
				$data = array(
					'start_date' => time(), // 结算时间
					'end_date'   => time(), // 结算截止时间
					'create_date'=> time(), // 记录创建时间
					'store_id'   => $store_id, // 店铺id
				);
                if($list['coupon_id'] != 0){
                    $couponStore_id = M('coupon')->where(['id'=>$list['coupon_id']])->getField('store_id');
                    if($couponStore_id > 0){
                        $list['total_amount'] = $list['order_amount'];
                    }
                }

					$commis_totals=0;
					
					if($list['dai_type']==2){
						$commis_totals=$number=$list['total_amount']*$order_goods[0]['points']/100;
						//$number *= -1;
					}else{
						foreach($order_goods as $vss){
							$commis_totals+=$vss['points']*$vss['member_goods_price']*$vss['goods_num']/100;
						}
					}
					if($list['shi_price']>0)
						$list['total_amount']=$list['shi_price'];

                    $coupon_price = $list['coupon_price'] ?? 0;
					$data['order_sn'] = $list['order_sn'];// 订单商品金额
					$data['order_totals'] =$list['total_amount'];// 订单商品金额
					$data['shipping_totals'] = $list['shipping_price'];// 运费
					$data['commis_totals'] =  \sanwei($commis_totals);// 平台费用
					$data['result_totals'] = $list['total_amount']-sanwei($commis_totals); //+$list['integral_money'];// 本期应结
					$data['discount_totals'] =  $list['discount'];// 改单价
                    $data['coupon_price'] =  $coupon_price;// 优惠价
					
					//M('users')->where("user_id =".$list['user_id'])->setInc('total_amount',$list['order_amount']); // 用户消费记录+n

					M('order_statis')->add($data); // 添加一笔结算统计
                    
                    M("order")->where('order_id='.$order_id)->save([
                        'order_status'=>'2',
                        'pay_status'=>'1',
                        'pda_checkout'=>'1',
                        'is_checkout'=>1
                    ]);
                    $order_ids .= $order_id.',';
                    M('users_price')->where('order_id='.$order_id)->setField(['status'=>2]);
					// 给商家加钱 记录日志
					storeAccountLog($store_id,$data['result_totals'],$data['result_totals'] * -1,'平台订单结算');
					//开始计算积分
					accountLog($list['user_id'],0,$list['total_amount'],'订单 '.$list['order_sn'].' 赠送的积分！',0,$list['order_id'],$list['total_amount']);
				
			$myorders.=$order_id.',';
			}
			adminLog('批量确认收款:'.$order_ids);
		echo $myorders;
		exit;
		}
	 }
     /*
	 *异常订单
	 */
    public function unusual(){
        $condition = array();$myw=' ';
        $session_fenbu = session('fenbu_id');
        $fenbu_id = I('fenbu_id');
        if($fenbu_id == '' && $session_fenbu == '0'){
            
             $fenbu = M('fenbu')->field('fenbu_id')->select();
            $fenbu_ids = '';
            foreach ($fenbu as $v){
                $fenbu_ids.= $v['fenbu_id'].',';
            }
            $fenbu_ids = substr($fenbu_ids,0,-1);
            $condition['a.ufenbu_id'] = ['in',$fenbu_ids];
        }else{
            if($session_fenbu == '0'){
                $condition['a.ufenbu_id'] = $fenbu_id;
            }else{
                $condition['a.ufenbu_id'] = session('fenbu_id');
            }
        }
       
        I('kehu') ? $condition['c.company'] = array('like','%'.trim(I('kehu')).'%') : false;
        I('shanghu') ? $condition['d.store_name'] = array('like','%'.trim(I('shanghu')).'%') : false;

        I('order_sn') ? $condition['order_sn'] =  array('like','%'.trim(I('order_sn')).'%') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;

        $condition['a.order_status'] = 1;//判断要列出的订单状态
        $condition['_string'] = '(a.order_status = 1 and a.jian_count > 0 and a.ruku_count != a.jian_count and a.ruku_count > 0) or (a.pda_qdzt = 1)';

        if(I('biaoshi_xian')){
            $condition['c.biaoshi_xian'] = I('biaoshi_xian');
            $myw.=' and c.biaoshi_xian="'.I('biaoshi_xian').'"';
        }


        if(I('tag')){
            if(I('tag') == 1){
                $condition['a.tag_price'] = ['eq',0];
                $myw.=" AND a.tag_price = 0 ";
            }else{
                $condition['a.tag_price'] = ['neq',0];
                $myw.=" AND a.tag_price <> 0 ";
            }
        }

        if(I('unusual_type')){
            if(I('unusual_type') == 1){
                $condition['a.pda_qdzt'] = 0;
                $myw.=' and a.pda_qdzt=0';
            }else{
                $condition['a.pda_qdzt'] = 1;
                $myw.=' and a.pda_qdzt=1';
            }
        }


        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }

        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
            $myw.=' and a.add_time > "'.$begin.' " and  a.add_time < "'.$end.'" ' ;
        }
        
        $count = M('order a')
            ->field('a.user_id,SUM(order_amount) as order_amount')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->where($condition)->order('a.order_id desc')->group('a.user_id')
            ->select();


        $Page  = new Page2(count($count),$_GET['num']);

        //获取订单列表
        $orderList = M('order a')
            ->field('a.order_id,a.user_id,c.nickname,c.company,CONCAT(c.biaoshi_xian,if(c.fast_flag="1","快","")) as biaoshi_xian')
//             ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->where($condition)
            ->limit("$Page->firstRow,$Page->listRows ")
            ->order('a.order_id desc')
            ->group('a.user_id')->select(); //过滤获取主订单

  
        foreach($orderList as $key=>$v) { //整理子单
            $order_list = M('order a')
                ->field('a.order_id,a.pda_qdzt,a.order_status,a.jian_count,a.ruku_count as ruku_count,a.order_sn,a.store_id,a.jian_count,a.order_amount,a.pda_qdzt,a.tag_price,c.nickname,c.company,d.store_name,CONCAT(c.biaoshi_xian,if(c.fast_flag="1","快","")) as biaoshi_xian,a.ruku_count,a.chuku_count,a.is_checkout,a.admin_note,a.ruku_last_time')
                ->join('ty_users c on a.user_id=c.user_id', 'LEFT')
                ->join('ty_store d on a.store_id=d.store_id', 'LEFT')
                ->where('a.user_id=' . $v['user_id'] . ' and a.order_status=1  and a.jian_count > 0 and a.ruku_count != a.jian_count'. $myw)
                ->group('a.order_id')
//                 ->group('b.order_id')
                ->order('a.order_id desc')
                ->select(); //过滤获取主订单

            $xiaoji = 0;
            foreach ($order_list as $keys => $values) { //整理子单
                $rukunum = $values['ruku_count'];
                $chukunum = $values['chuku_count'];
                $order_list[$keys]['ruku'] = $rukunum;
                $order_list[$keys]['chuku'] = $chukunum;
                $order_list[$keys]['pda_online'] = $values['pda_online']!=0 ?$values['pda_online'] : $values['order_amount'];
//                 $pda_online +=$order_list[$keys]['pda_online'];
//                 $pda_offline += $values['pda_offline'];
                $xiaoji += sanwei($values['order_amount']);
                $zongji+=$values['order_amount']+$values['yijia_heji'];
            }
            $orderList[$key]["xiaoji"] = $xiaoji;
            $orderList[$key]["order_list"] = $order_list;
        }

        //echo json_encode($orderList);
        $store_list = M('store')->getField('store_id,store_name');
        $this->assign('store_list',$store_list);
        $this->assign('show',$Page->show());
        $this->assign('list',$orderList);
        $this->assign('fenbu_list',$this->fenbu_list);
        C('TOKEN_ON',false);
        $this->display();
    }
	 
	 
	 /**
     * 异常订单导出
     */
    public function export_unusual()
    {

        $condition = array();$myw=' ';
        $session_fenbu = session('fenbu_id');
        $fenbu_id = I('fenbu_id');
        if($fenbu_id == '' && $session_fenbu == '0'){
            
             $fenbu = M('fenbu')->field('fenbu_id')->select();
            $fenbu_ids = '';
            foreach ($fenbu as $v){
                $fenbu_ids.= $v['fenbu_id'].',';
            }
            $fenbu_ids = substr($fenbu_ids,0,-1);
            $condition['a.ufenbu_id'] = ['in',$fenbu_ids];
        }else{
            if($session_fenbu == '0'){
                $condition['a.ufenbu_id'] = $fenbu_id;
            }else{
                $condition['a.ufenbu_id'] = session('fenbu_id');
            }
        }
       
        I('kehu') ? $condition['c.company'] = array('like','%'.trim(I('kehu')).'%') : false;
        I('shanghu') ? $condition['d.store_name'] = array('like','%'.trim(I('shanghu')).'%') : false;

        I('order_sn') ? $condition['order_sn'] =  array('like','%'.trim(I('order_sn')).'%') : false;
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;

        $condition['a.order_status'] = 1;//判断要列出的订单状态
        $condition['_string'] = '(a.order_status = 1 and a.jian_count > 0 and a.ruku_count != a.jian_count and a.ruku_count > 0) or (a.pda_qdzt = 1)';

        if(I('biaoshi_xian')){
            $condition['c.biaoshi_xian'] = I('biaoshi_xian');
            $myw.=' and c.biaoshi_xian="'.I('biaoshi_xian').'"';
        }


        if(I('tag')){
            if(I('tag') == 1){
                $condition['a.tag_price'] = ['eq',0];
                $myw.=" AND a.tag_price = 0 ";
            }else{
                $condition['a.tag_price'] = ['neq',0];
                $myw.=" AND a.tag_price <> 0 ";
            }
        }

        if(I('unusual_type')){
            if(I('unusual_type') == 1){
                $condition['a.pda_qdzt'] = 0;
                $myw.=' and a.pda_qdzt=0';
            }else{
                $condition['a.pda_qdzt'] = 1;
                $myw.=' and a.pda_qdzt=1';
            }
        }


        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }

        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
            $myw.=' and a.add_time > "'.$begin.' " and  a.add_time < "'.$end.'" ' ;
        }
  
        //获取订单列表
        $orderList = M('order a')
            ->field('a.order_id,a.user_id,c.nickname,c.company,CONCAT(c.biaoshi_xian,if(c.fast_flag="1","快","")) as biaoshi_xian')
//             ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->where($condition)
            ->order('a.order_id desc')
            ->group('a.user_id')->select(); //过滤获取主订单

  
        foreach($orderList as $key=>$v) { //整理子单
            $order_list = M('order a')
                ->field('a.order_id,a.pda_qdzt,a.order_status,a.jian_count,a.ruku_count as ruku_count,a.order_sn,a.store_id,a.jian_count,a.order_amount,a.pda_qdzt,a.tag_price,c.nickname,c.company,d.store_name,CONCAT(c.biaoshi_xian,if(c.fast_flag="1","快","")) as biaoshi_xian,a.ruku_count,a.chuku_count,a.is_checkout,a.admin_note,a.ruku_last_time')
                ->join('ty_users c on a.user_id=c.user_id', 'LEFT')
                ->join('ty_store d on a.store_id=d.store_id', 'LEFT')
                ->where('a.user_id=' . $v['user_id'] . ' and a.order_status=1  and a.jian_count > 0 and a.ruku_count != a.jian_count'. $myw)
                ->group('a.order_id')
//                 ->group('b.order_id')
                ->order('a.order_id desc')
                ->select(); //过滤获取主订单
            $xiaoji = $i=0;;
            foreach ($order_list as $keys => $values) { //整理子单
                $rukunum = $values[$this->z.'ruku_count'];
                $chukunum = $values[$this->z.'chuku_count'];
                $order_list[$keys]['ruku'] = $rukunum;
                $order_list[$keys]['chuku'] = $chukunum;
                $order_list[$keys]['pda_online'] = $values['pda_online']!=0 ?$values['pda_online'] : $values['order_amount'];
                $xiaoji += sanwei($values['order_amount']);
                $zongji+=$values['order_amount']+$values['yijia_heji'];
            }
            $orderList[$key]["xiaoji"] = $xiaoji;
            $orderList[$key]["order_list"] = $order_list;
        }



        $strTable ='<table style="width:210mm;table-layout:fixed" border="1">';
        $strTable .= '<tr style="font-weight:bold">';
        $strTable .= '<td style="text-align:center;font-size:12px;width:95px;height:35px;">序号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:100px;">客户名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:100px;">订单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:52px;">件数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:105px;">商家名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:50px;">回款状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:65px;">小计金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:65px;">合计金额</td>';

        $strTable .= '</tr>';

        foreach($orderList as $vs){
            $strTables='';$i++;
            foreach($vs['order_list'] as $vss){
                $strTables .= '<tr>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:100px">'.$vss['order_sn'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.$vss['jian_count'].'->'.$vss['ruku'].'->'.$vss['chuku'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.$vss['store_name'].'</td>';
                if($vss['tag_price']){
                    $strTables .= '<td style="text-align:center;font-size:12px;height:35px">已回款</td>';
                }else{
                    $strTables .= '<td style="text-align:center;font-size:12px;height:35px">未回款</td>';
                }
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px;color:red">'.($vss['order_amount']+$vss['yijia_heji']).'</td>';
                $strTables .= '</tr>';
            }


            $strTable .= '<tr style="border:1px solid #000">
		<td style="text-align:center;font-size:12px;border:1px;width:50px;">'.$i.'</td>
		<td style="text-align:center;font-size:12px;border:1px;width:100px;WORD-WRAP:break-all;">'.$vs['company'].$vss['biaoshi_xian'].'</td>
		<td colspan="5">
		<table width="650" border="1">
		'.$strTables.'
		</table>
		</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold">'.($vs['xiaoji']).'</td>
		</tr>';
        }

        $strTable .= '<tr style="border:1px solid #000">
		<td colspan="6" style="text-align:right;font-weight:bold;height:32px">
		合计：
		</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold">'.$zongji.'</td>
		</tr>';
        $strTable .='</table>';

        unset($orderList);
        downloadExcel($strTable,'order');
        exit();
    }
    public function pda_master_piliang(){
        $action=I('action');$datas=I('datas');
        $pda_open=tpCache("basic")['pda_open'];
        if(!empty($action) && !empty($datas)){
            if($pda_open==0){
                exit;
            }
            $datas=\explode(',',$datas);
            $myorders='';
            foreach($datas as $v){
                $order_ids = M('order')->where(['master_order_sn'=>$v])->getField('order_id,store_id');
                foreach ($order_ids as $key=>$item){
                    $order_id=$key;
                    $store_id=$item;

                    $order_list=M("order_goods")->field('goods_id,goods_num')->where('order_id='.$order_id)->select();//更新产品销量
                    foreach($order_list as $vv){
                        M('goods')->where('goods_id='.$vv['goods_id'])->setInc('sales_sum',(int)$vv['goods_num']);
                    }


                    //溢价状态
                    M("order_yijia")->where('order_id='.$order_id)->setField('yijia_status','1');


                    M("order")->where('order_id='.$order_id)->save([
                        'order_status'=>'2',
                        'pay_status'=>'1',
                        'pda_checkout'=>'1',
                        'is_checkout'=>1
                    ]);

                    //开始结算
                    $list = M('order')->where('order_id='.$order_id)->find();
                    $order_statis = M('order_statis')->where(['order_sn'=>$list['order_sn']])->find();
                    if($order_statis){
                        continue;
                    } // 没有数据直接跳出


                    $data = array(
                        'start_date' => time(), // 结算时间
                        'end_date'   => time(), // 结算截止时间
                        'create_date'=> time(), // 记录创建时间
                        'store_id'   => $store_id, // 店铺id
                    );

                    $order_goods = M('order_goods')->where(array('order_id' => $order_id))->select();//订单商品列表
                    $commis_totals=0;

                    if($list['dai_type']==2){
                        $commis_totals=$number=$list['order_amount']*$order_goods[0]['points']/100;
                        //$number *= -1;
                    }else{
                        foreach($order_goods as $vss){
                            $commis_totals+=$vss['points']*$vss['member_goods_price']*$vss['goods_num']/100;
                        }
                    }
                    if($list['shi_price']>0)
                        $list['order_amount']=$list['shi_price'];

                    $coupon_price = $list['coupon_price'] ?? 0;
                    $data['order_sn'] = $list['order_sn'];// 订单商品金额
                    $data['order_totals'] =$list['total_amount'];// 订单商品金额
                    $data['shipping_totals'] = $list['shipping_price'];// 运费
                    $data['commis_totals'] =  \sanwei($commis_totals);// 平台费用
                    $data['result_totals'] = $list['total_amount']-sanwei($commis_totals); //+$list['integral_money'];// 本期应结
                    $data['discount_totals'] =  $list['discount'];// 改单价
                    $data['coupon_price'] =  $coupon_price;// 优惠价

                    //M('users')->where("user_id =".$list['user_id'])->setInc('total_amount',$list['order_amount']); // 用户消费记录+n

                    M('order_statis')->add($data); // 添加一笔结算统计
                    M('users_price')->where('order_id='.$order_id)->setField(['status'=>2]);


                    // 标识为已经结算

                    // 给商家加钱 记录日志
                    storeAccountLog($store_id,$data['result_totals'],$data['result_totals'] * -1,'平台订单结算');
                    //开始计算积分
                    accountLog($list['user_id'],0,$list['order_amount'],'订单 '.$list['order_sn'].' 赠送的积分！',0,$list['order_id'],$list['order_amount']);

                    $myorders.=$order_id.',';
                }
            }
            echo $myorders;
            exit;
        }
    }
    
    
    /*
    *财务对账
    */
    public function storeCount(){
        $p = I('p',1);
		$start = ($p-1)*16;
		$cat_id = I('cat_id',0);
		$brand_id = I('brand_id',0);
		$kehu= trim(I('kehu'));
		//$begin=str_replace('+', ' ', I('begin'));$end=str_replace('+', ' ', I('end'));
		
		$heji=0;
	    $fenbu_id = I('fenbu_id');
// 		$fenbu_id=I('fenbu_id') ? I('fenbu_id') : \session('fenbu_id');
		
// 		$fenbu_ids=$fenbu_id ? $fenbu_id : '0,31,32,33,34,37,42';
        $fenbu_ids = $fenbu_id;
        if($fenbu_id == ''){
             $fenbu = M('fenbu')->field('fenbu_id')->select();
            $fenbu_ids = '';
            foreach ($fenbu as $v){
                $fenbu_ids.= $v['fenbu_id'].',';
            }
            $fenbu_ids = substr($fenbu_ids,0,-1);
            // $fenbu_ids = '0,31,32,33,34,37,42';
        }
		//店铺查询趋势 废除store_moneys 
		//$count=M()->query("SELECT a.store_id from ty_store a where store_name like '%$kehu%' order by a.store_id desc");
		$count=M('store')->where("store_name like '%$kehu%'")->getField('store_id',true);

		if($kehu && $count){
			$where="a.chuku_last_time>=$this->begin and a.chuku_last_time<=$this->end and ufenbu_id in($fenbu_ids) and (order_status in(1,2)) and ruku_count = chuku_count and chuku_count!=0 and b.store_name like '%$kehu%'";
			$hejis=M('order')->field('sum(order_amount) as heji,sum(kou_price) as kou')->where("chuku_last_time>$this->begin and chuku_last_time<$this->end and ufenbu_id in($fenbu_ids) and order_status in(1,2) and ruku_count = chuku_count and chuku_count!=0 and  store_id in(".join(',',$count).")")->select(); //销售额合计 shadow.$count[0]['store_id']
		
		}else{
			$where="a.chuku_last_time>=$this->begin and a.chuku_last_time<=$this->end and a.ufenbu_id in($fenbu_ids) and a.order_status in(1,2) and ruku_count = chuku_count and chuku_count!=0";
			$hejis=M('order')->field('sum(order_amount) as heji,sum(kou_price) as kou')->where("chuku_last_time>=$this->begin and chuku_last_time<=$this->end and (order_status in(1,2)) and ruku_count = chuku_count and chuku_count!=0 and ufenbu_id in($fenbu_ids)")->select(); //销售额合计 shadow
		}
		
	
		$total = M('order a')
        ->field("sum(a.order_amount) xiaoshoue,sum(a.kou_price) kou_price,GROUP_CONCAT(rg.member_goods_price SEPARATOR '||') AS member_goods_price,GROUP_CONCAT(rg.status SEPARATOR '||') AS return_status,GROUP_CONCAT(rg.goods_num SEPARATOR '||') AS rggoods_num,a.ufenbu_id,b.store_id,b.store_name,b.store_phone,a.order_id")
        ->join("ty_store b on a.store_id=b.store_id")
        ->join('ty_return_goods rg on rg.order_id = a.order_id', 'LEFT')
        ->where($where)
        ->group("a.store_id")
        ->order("xiaoshoue desc")
        ->limit($start, 16)
        ->select();
		
        $tuihuo = 0;
		foreach($total as $key=>$v){
// 			$order_list= M()->query("select sum(kou_price) kou_price from ty_order where chuku_last_time>$this->begin and chuku_last_time<$this->end and store_id=".$v['store_id']." and order_status in(1,2) and ruku_count = chuku_count and chuku_count!=0 ");
// 			$total[$key]['danshu']=$order_list[0]['danshu']; //单数
// 			$total[$key]['renshu']=count(M('order')->field('order_id')->where("chuku_last_time>$this->begin and chuku_last_time<$this->end and store_id=".$v['store_id']." and order_status in(1,2) and ruku_count = chuku_count and chuku_count!=0 ")->group('user_id')->select()); //人数
			
// 			$total[$key]['kou_price']=$order_list[0]['kou_price']; //扣点收入
             $total[$key]['tuihuo'] = 0;
            if(!empty($v['member_goods_price'])){
                $v['member_goods_price'] = explode('||', $v['member_goods_price']);
                $v['return_status'] = explode('||', $v['return_status']);
                $v['rggoods_num'] = explode('||', $v['rggoods_num']);
                
                foreach ($v['member_goods_price'] as $k=>$val){
                   if($v['return_status'][$k] != 3){
                       $total[$key]['tuihuo'] += $v['member_goods_price'][$k]*$v['rggoods_num'][$k];
                   }
                }
            }
            $tuihuo += $total[$key]['tuihuo'];
            
		}
        // dump($total);
		$Page = new \Think\Page(\count($count),16);
		$show = $Page->show();
		$this->assign('page',$show);
		$this->assign('fenbu_list',$this->fenbu_list);

		$this->assign([
			'list'=>$total,
			'heji'=>$hejis[0]['heji'],
			'heji_k'=>$hejis[0]['kou'],
			'tuihuo'=>$tuihuo,
			'begin'=>$this->begin,
			'end'=>$this->end
		]);
		$this->display();
    }
    
    public function export_storeCount()
    {
     
		$kehu= trim(I('kehu'));
		$heji=0;
	    $fenbu_id = I('fenbu_id');
        $fenbu_ids = $fenbu_id;
        if($fenbu_id == ''){
             $fenbu = M('fenbu')->field('fenbu_id')->select();
            $fenbu_ids = '';
            foreach ($fenbu as $v){
                $fenbu_ids.= $v['fenbu_id'].',';
            }
            $fenbu_ids = substr($fenbu_ids,0,-1);
        }

		$count=M('store')->where("store_name like '%$kehu%'")->getField('store_id',true);

		if($kehu && $count){
			$where="a.chuku_last_time>$this->begin and a.chuku_last_time<$this->end and ufenbu_id in($fenbu_ids) and (order_status in(1,2)) and ruku_count = chuku_count and chuku_count!=0 and b.store_name like '%$kehu%'";
			$hejis=M('order')->field('sum(order_amount) as heji,sum(kou_price) as kou')->where("chuku_last_time>$this->begin and chuku_last_time<$this->end and ufenbu_id in($fenbu_ids) and order_status in(1,2) and ruku_count = chuku_count and chuku_count!=0 and  store_id in(".join(',',$count).")")->select(); //销售额合计 shadow.$count[0]['store_id']
		
		}else{
			$where="a.chuku_last_time>$this->begin and a.chuku_last_time<$this->end and a.ufenbu_id in($fenbu_ids) and a.order_status in(1,2) and ruku_count = chuku_count and chuku_count!=0";
			$hejis=M('order')->field('sum(order_amount) as heji,sum(kou_price) as kou')->where("chuku_last_time>$this->begin and chuku_last_time<$this->end and (order_status in(1,2)) and ruku_count = chuku_count and chuku_count!=0 and ufenbu_id in($fenbu_ids)")->select(); //销售额合计 shadow
		}
		$total = M('order a')
        ->field("sum(a.order_amount) xiaoshoue,sum(a.kou_price) kou_price,GROUP_CONCAT(rg.member_goods_price SEPARATOR '||') AS member_goods_price,GROUP_CONCAT(rg.status SEPARATOR '||') AS return_status,GROUP_CONCAT(rg.goods_num SEPARATOR '||') AS rggoods_num,a.ufenbu_id,b.store_id,b.store_name,b.store_phone,a.order_id")
        ->join("ty_store b on a.store_id=b.store_id")
        ->join('ty_return_goods rg on rg.order_id = a.order_id', 'LEFT')
        ->where($where)
        ->group("a.store_id")
        ->order("xiaoshoue desc")
        ->select();
		
        $tuihuo = 0;
		foreach($total as $key=>$v){

             $total[$key]['tuihuo'] = 0;
            if(!empty($v['member_goods_price'])){
                $v['member_goods_price'] = explode('||', $v['member_goods_price']);
                $v['return_status'] = explode('||', $v['return_status']);
                $v['rggoods_num'] = explode('||', $v['rggoods_num']);
                
                foreach ($v['member_goods_price'] as $k=>$val){
                   if($v['return_status'][$k] != 3){
                       $total[$key]['tuihuo'] += $v['member_goods_price'][$k]*$v['rggoods_num'][$k];
                   }
                }
            }
            $tuihuo+=$total[$key]['tuihuo'];
		}

        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">ID</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">店铺名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">联系电话</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">销售金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台扣点</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">扣点后金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">退货金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">应结算金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">最后出库时间</td>';
        $strTable .= '</tr>';
        foreach($total as $k=>$val){
            $a = $val['xiaoshoue']-$val['kou_price'];
            $b = $a-$val['tuihuo'];
            unset($total);
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['store_id'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['store_name'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['store_phone'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['xiaoshoue'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['kou_price'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$a.'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['tuihuo'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$b.'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.\date('Y-m-d H:i:s',$this->begin).'-'.\date('Y-m-d H:i:s',$this->end).' </td>';
            $strTable .= '</tr>';
        }
        $heji=$hejis[0]['heji'];
		$heji_k=$hejis[0]['kou'];
        $c = $heji-$heji_k;
        $d = $c-$tuihuo;
        $strTable .= '<td style="text-align:left;font-size:12px;text-align:right;" colspan="3">合计</td>';
        $strTable .= '<td style="text-align:left;font-size:12px;" >'.$heji.'</td>';
        $strTable .= '<td style="text-align:left;font-size:12px;" >'.$heji_k.'</td>';
        $strTable .= '<td style="text-align:left;font-size:12px;" >'.$c.'</td>';
        $strTable .= '<td style="text-align:left;font-size:12px;" ></td>';
        $strTable .= '<td style="text-align:left;font-size:12px;" ></td>';
        $strTable .= '<td style="text-align:left;font-size:12px;" ></td>';
        $strTable .='</table>';
        unset($total);
        downloadExcel($strTable,'财务对账');
        exit();
    }

    
    

     public function pda(){
        $order_sn = I('order_sn');
		$kehu = I('kehu');$shanghu = I('shanghu');
        $timegap = I('timegap');
		$pda = I('pda');
		$pda_open=tpCache("basic")['pda_open'];
		//$where['shipping_status'] =1; 
		$action=$_POST['action'];
		$biaozhu=$_POST['biaozhu'];$tag_price=I('tag_price');
		$order_id=I('order_id');
        $tag=I('tag');
		$store_id=I('store_id');
		$shoukuan=I('shoukuan');
		$driver=I('driver');
		$wheres="a.order_status <3 ";

         $chuku_time = I('chuku_time');



		if(\session('fenbu_id')!=0){
			$wheres.=" and a.ufenbu_id=".\session('fenbu_id');
		}


		
		if(!empty($action) && !empty($order_id)){
			if($pda_open==0){
				echo '1';exit;
			}
			//更新产品销量
			$order_list=M("order_goods")->field('goods_id,goods_num')->where('order_id='.$order_id)->select();
			foreach($order_list as $v){
				M('goods')->where('goods_id='.$v['goods_id'])->setInc('sales_sum',(int)$v['goods_num']);
			}
			M("order")->where('order_id='.$order_id)->save([
				'order_status'=>'2',
				'pay_status'=>'1',
				'pda_checkout'=>'1'
			]);
			 //溢价状态
			M("order_yijia")->where('order_id='.$order_id)->setField('yijia_status','1');
			M('users_price')->where('order_id='.$order_id)->setField(['status'=>2]);
			
			//开始结算
			$list = M('order')->where('order_id='.$order_id.' and is_checkout=0 and order_status in(2,4)')->find();
			
			if(empty($list)) // 没有数据直接跳出
			    return false;
			
			$data = array(
				'start_date' => time(), // 结算时间
				'end_date'   => time(), // 结算截止时间
				'create_date'=>  time(), // 记录创建时间
				'store_id'   => $store_id, // 店铺id
			);
            //如果是店铺优惠券，只结算使用优惠券的金额给到商家
            if($list['coupon_id'] != 0){
                $couponStore_id = M('coupon')->where(['id'=>$list['coupon_id']])->getField('store_id');
                if($couponStore_id > 0){
                    $list['total_amount'] = $list['order_amount'];
                }
            }
				$order_goods = M('order_goods')->where(array('order_id' => $order_id))->select();//订单商品列表
				$commis_totals=0;
				
				if($list['dai_type']==2){
					$commis_totals=$number=$list['total_amount']*$order_goods[0]['points']/100;
					//$number *= -1;
				}else{
					foreach($order_goods as $vss){
						$commis_totals+=$vss['points']*$vss['member_goods_price']*$vss['goods_num']/100;
					} 
				}
				if($list['shi_price']>0)
					$list['total_amount']=$list['shi_price'];
				
				$data['result_totals'] =$list['total_amount']-sanwei($commis_totals); //+$list['integral_money'];// 本期应结
				
				$data['order_sn'] = $list['order_sn'];// 订单商品金额
			    $data['order_totals'] =$list['total_amount'];// 订单商品金额
			    $data['shipping_totals'] = $list['shipping_price'];// 运费    
			    $data['commis_totals'] =  \sanwei($commis_totals);// 平台费用
			    $data['discount_totals'] =  $list['discount'];// 改单价
			                 
			    M('order')->where("order_id =".$list['order_id'])->save(array('is_checkout' =>1)); // 标识为已经结算
				M('order_statis')->add($data); // 添加一笔结算统计
                adminLog('确认收款了订单id：'.$list['order_id']);
				// 给商家加钱 记录日志
				storeAccountLog($store_id,$data['result_totals'],$data['result_totals'] * -1,'平台订单结算');
				//开始计算积分
				accountLog($list['user_id'],0,$list['total_amount'],'订单 '.$list['order_sn'].' 赠送的积分！',0,$list['order_id']);
			exit;
		}
		
		if(!empty($biaozhu) && !empty($order_id)){
			M("order")->where('order_id='.$order_id)->setField('tag_price',$tag_price);
		}

			$wheres.="and a.jian_count >0 AND a.ruku_count = a.chuku_count AND a.chuku_last_time > ".$this->begin." AND a.chuku_last_time < ".$this->end." ";

		if($pda){
			//$where['pda_name_ruku'] = $pda;
			$wheres.=" AND ".$this->z."pda_name_ruku= '$pda' AND ".$this->z."status_r=1 AND a.order_status <> 5 ";
		}

         if($driver){
             $wheres.=" AND g.nick_name like '%".$driver."%' ";
         }

		if($tag){
		    if($tag == 1){
                $wheres.=" AND a.tag_price = 0 ";
            }else{
                $wheres.=" AND a.tag_price <> 0 ";
            }
        }

		//$where['status_r'] =1;$where['a.order_status'] =['neq',5];
		if($shoukuan!=""){
			//$where['pda_checkout'] =$shoukuan;
			$wheres.=" AND pda_checkout=$shoukuan ";
		}
		I('biaoshi') && $wheres.=" AND f.biaoshi_xian='".I('biaoshi')."' "; //$where['f.biaoshi_xian'] = I('biaoshi');

        $order_sn && $wheres.=" AND order_sn like '%".$order_sn."%' "; //$where['order_sn'] = array('like','%'.$order_sn.'%');

		$kehu && $wheres.=" AND (f.company like '%".$kehu."%' or a.consignee like '%".$kehu."%') "; //$where['company'] = ['like',"%$kehu%"];
		$shanghu && $wheres.=" AND store_name like '%".$shanghu."%' "; //$where['_string'] = '(store_name like "%'.$shanghu.'%")';
        
		$count =M()->query("SELECT a.total_amount,a.integral_money,a.order_amount,a.yijia_heji,(select sum(e.member_goods_price*e.goods_num*e.points/100) from ty_order_goods e where e.order_id=a.order_id) as pprice FROM ty_order a  LEFT JOIN ty_store d on a.store_id=d.store_id LEFT JOIN ty_users f on a.user_id=f.user_id LEFT JOIN ty_users g on a.driver_id=g.user_id WHERE $wheres ORDER BY a.order_id desc");

         $Page = new Page2(count($count),$_GET['num']);

		$list =M()->query("SELECT a.chuku_last_time,a.ruku_last_time,a.order_sn,a.pay_status,a.shi_price,a.store_id,a.is_checkout,a.consignee,a.mobile,a.tag_price,a.jian_count,a.dai_type,a.total_amount,a.order_amount,a.yijia_heji,a.order_id,a.discount,d.store_name,a.pda_checkout,a.user_id,a.integral_money,f.biaoshi_xian,g.nick_name as driver_name,a.coupon_price FROM ty_order a  LEFT JOIN ty_store d on a.store_id=d.store_id LEFT JOIN ty_users f on a.user_id=f.user_id LEFT JOIN ty_users g on a.driver_id=g.user_id WHERE $wheres  ORDER BY f.xsort,a.order_id desc limit $Page->firstRow,$Page->listRows ");

$xprice=$pprice=$yprice=0;
		foreach($count as $key=>$v){ //统计价格->field('sum(member_goods_price*goods_num*points/100) as pprice')
			$xprice+=($v['order_amount']+$v['yijia_heji'])-$v['integral_money'];
			$pprice+=$v['pprice'];
		}	
		$this->assign('xprice',\sanwei($xprice));
		$this->assign('pprice',\sanwei($pprice));
		$this->assign('yprice',\sanwei($xprice-$pprice));
		
		foreach($list as $key=>$v){ //循环计算扣点
			$list[$key]['company']=M('users')->where('user_id='.$v['user_id'])->getField('company');
			$list[$key]['pprice']=order_price($v['order_id'])['points_count'];
			$list[$key]['order_amount']=$v['order_amount']+$v['yijia_heji'];
		}

		$pda_list=M("pda")->where('fenbu_id='.\session('fenbu_id'))->select();
        $show  = $Page->show();
		$this->assign('pda_list',$pda_list);
        $this->assign('show',$show);
		$this->assign('pda_open',$pda_open);
        $this->assign('list',$list); 
		$this->assign('z',$this->z);
        C('TOKEN_ON',false);
        $this->display();
	 }



    public function pda_new(){
        $condition = array();$myw=' ';
        I('kehu') ? $condition['c.company'] = array('like','%'.trim(I('kehu')).'%') : false;
        I('shanghu') ? $condition['d.store_name'] = array('like','%'.trim(I('shanghu')).'%') : false;
        $action=$_POST['action'];$order_ids=$_POST['datas'];$str=$_POST['str'];
        $shoukuan=I('shoukuan');
        $order1 = 'c.xsort asc';
        $order2 = 'a.order_id desc';
//         $store_name = I('store_name'); $store_ids='';
//         if($store_name)
//         {
//             $store_id_arr = M('store')->where("store_name like '%$store_name%'")->getField('store_id');
//             if($store_id_arr)
//             {
//                 $store_ids="a.store_id=".$store_id_arr;
//
//             }
//         }

        //I('order_sn') ? $condition['order_sn'] =  array('like','%'.trim(I('order_sn')).'%') : false;

        if(I('order_sn') ){
            $subQuery_orderIds = M()->query('select order_id from ty_order WHERE LOCATE('.I('order_sn').',order_sn) > 0');
            foreach ($subQuery_orderIds as $item){
                $ids[] = $item['order_id'];
            }
            if($ids){
                $condition['a.order_id'] = ['in',join(',',$ids)];
            }else{
                $condition['a.order_id'] = 0;
            }

        }
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        I('biaoshi_xian') && $condition['c.biaoshi_xian'] = I('biaoshi_xian');
        $order_status_title = I('order_status_title');
        
            if($order_status_title == 1 ){
                $condition['a.order_status_title'] = 0;
                $myw .= ' and a.order_status_title = 0';
            }elseif($order_status_title == 2 ){
                $condition['a.order_status_title'] = 1;
                $myw .= ' and a.order_status_title = 1';
            }elseif($order_status_title == 3 ){
                $condition['a.order_status_title'] = 2;
                $myw .= ' and a.order_status_title = 2';
            }
      

        $condition['a.order_status'] = ['lt',3];//判断要列出的订单状态
        $condition['a.shipping_status'] = 1;
        $condition['a.pda_qdzt'] = 0;
        $condition['a.ruku_count'] = ['gt',0];
        $condition['a.chuku_count'] = ['gt',0];
        $condition['_string'] = '(a.ruku_count = a.jian_count and a.chuku_count = a.ruku_count and a.ruku_last_time is not null and a.chuku_last_time is not null and a.driver_id > 0)';

        if(I('driver')){
            $condition['e.nick_name'] = I('driver');
            $myw.=' and e.nick_name = "'.I('driver').'" ';
        }

        if($shoukuan!=""){
            $condition['a.pda_checkout'] = $shoukuan;
            $condition['a.is_checkout'] = $shoukuan;
            $myw.=' and a.pda_checkout = "'.$shoukuan.'" ';
            $myw.=' and a.is_checkout = "'.$shoukuan.'" ';
        }

        if(I('duizhang_sn')){
            $orderIds = M('pda_duizhang')->where(['duizhang_sn'=>I('duizhang_sn')])->getField('order_ids');
            if($orderIds){
                $orderIds = json_decode($orderIds,true);
                $condition['a.order_id'] = ['in',join(',',$orderIds)];
                $myw.=' and a.order_id in ('.join(',',$orderIds).') ';
                $order1 = 'field(a.order_id,'.join(',',$orderIds).')';
                $order2 = 'field(a.order_id,'.join(',',$orderIds).')';
            }

        }else{
            if($this->begin && $this->end){
                $condition['a.chuku_last_time'] = array('between',"$this->begin,$this->end");
                $myw.=' and a.chuku_last_time > "'.$this->begin.' " and  a.chuku_last_time < "'.$this->end.'" ' ;
            }
        }

        if(I('tag')){
            if(I('tag') == 1){
                $condition['a.tag_price'] = ['eq',0];
                $myw.=" AND a.tag_price = 0 ";
            }else{
                $condition['a.tag_price'] = ['neq',0];
                $myw.=" AND a.tag_price <> 0 ";
            }
        }


        //echo \json_encode($condition);

        if($action=='yes' && !empty($order_ids)){
            $datas=\explode(',',$order_ids);
            $myorders='';
            foreach($datas as $v){
                $os=\explode('|',$v);
                $order_id=$os[0];
                M("order")->where('order_id='.$order_id)->setField('tag_price',1);
                $myorders.=$order_id.',';
            }
            echo $myorders;exit;
        }elseif($action=='zhuangtai' && !empty($order_ids)){
            $datas=\explode(',',$order_ids);
            $orderIds = [];
            foreach($datas as $v){
                $os=\explode('|',$v);
                $id=$os[0];
                $orderIds[] = $id;
            }
            $order_ids = join(',',$orderIds);
            M("order")->where('order_id in('.$order_ids.')')->setField('pda_qdzt',$str);

            if($str==0){
                M('order')->where('order_id in('.$order_ids.')')
                    ->setField([
                        'order_status'=>1,
                        'shipping_status'=>1,
                        'admin_note'=>null
                    ]);
                M("order_jian")->where('order_id in('.$order_ids.')')->setField([
                    'pda_name_ruku'=>'ddt_01',
                    'pda_name_chuku'=>'ddt_01',
                    'ruku_time'=>strtotime(date("Y-m-d H:i:s")),
                    'chuku_time'=>strtotime(date("Y-m-d H:i:s")),
                    'status_r'=>1,
                    'status_c'=>1
                ]);

            }elseif($str==1){
                foreach ($orderIds as $orid){
                    $pdzt_order = M('order')->where(['order_id'=>$orid])->find();
                    M('order')->where(['order_id'=>$orid])->save([
                        'pda_qdzt'=>1,
//                        'order_status'=>1,
//                        'shipping_status'=>1,
//                        'chuku_count'=>0,
//                        'chuku_last_time'=>null,
                        'admin_note'=>'缺货 入库时间：'.date('Y-m-d H:i',$pdzt_order['ruku_last_time']).' 出库时间：'.date('Y-m-d H:i',$pdzt_order['chuku_last_time'])
                    ]);
                }

//                 M('order')->where('order_id in('.$order_ids.')')
//                     ->setField();

//                M("order_jian")->where('order_id in('.$order_ids.')')->setField([
//                    'pda_name_chuku'=>null,
//                    'chuku_time'=>null,
//                    'status_c'=>0
//                ]);
            }elseif($str==2){
                $ciri = M('order')->where('order_id in('.$order_ids.')')->select();
                foreach ($ciri as $item){
                    $ruku_last_time = strtotime(date('Y-m-d H:i',strtotime('+1 day',$item['ruku_last_time']))); //次日送入库时间增加一天
                    M('order')->where(['order_id'=>$item['order_id']])->setField([
                        'admin_note'=>'次日送订单',
                        'chuku_count'=>0,
                        'chuku_last_time'=>null,
                        'pda_qdzt'=>2,
                        'ruku_last_time'=>$ruku_last_time
                    ]);

                    M("order_jian")->where(['order_id'=>$item['order_id']])->setField([
                        'ruku_time'=>$ruku_last_time,
                        'pda_name_chuku'=>null,
                        'chuku_time'=>null,
                        'status_c'=>0
                    ]);
                }



            }
            echo 1;exit;
        }
        
        $heji_price =$sum_price =$coupon_price=$order_count=0;
        // dump($condition);
        $count = M('order a')
            ->field('a.user_id,SUM(a.order_amount+yijia_heji) as total_amount,SUM(a.order_amount+yijia_heji) as order_amount,SUM(coupon_price) as coupon_price')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->join('ty_users e on a.driver_id=e.user_id','LEFT')
            ->where($condition)->order('a.order_id desc')->group('a.user_id')
            ->fetchSql()
            ->select();
        echo $count;exit;

        foreach ($count as $item){
            $heji_price += $item['order_amount'];
            $sum_price += $item['total_amount'];
            $coupon_price += $item['coupon_price'];
        }
        $order_count = count($count);

        // dump($condition);

        $Page  = new Page2(count($count), $_GET['num']);

        //获取订单列表
        $orderList = M('order a')
            ->field('a.order_id,a.user_id,c.nickname,c.company, c.biaoshi_xian,e.nick_name as driver_name,a.order_status_title')
//             ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->join('ty_users e on a.driver_id=e.user_id','LEFT')
            ->where($condition)
            ->limit("$Page->firstRow,$Page->listRows ")
            ->order($order1)
            ->group('a.user_id')->select(); //过滤获取主订单

        // foreach($orderList as $v){
        // 	$user_ids.=$v['user_id'].',';
        // }
        // $user_ids=\rtrim($user_ids,',');
        $order_status_title = I('order_status_title');
        $wheress = '';
        if(!empty($order_status_title)){
            $wheress = 'and a.order_status_title = '.$order_status_title;
        }
        $order_sn = I('order_sn');
        if(!empty($order_sn)){
            $myw .= "and a.order_sn like '%".$order_sn."%'";
        }
        
        foreach($orderList as $key=>$v) { //整理子单
            $order_list = M('order a')
                ->field('a.change,a.ruku_last_time,a.chuku_last_time,a.order_id,a.order_sn,a.store_id,a.jian_count,a.order_amount,a.tag_price,c.nickname,c.company,d.store_name,c.biaoshi_xian,a.ruku_count,a.chuku_count,a.is_checkout,a.admin_note,a.yijia_heji,a.coupon_price,a.total_amount,e.nick_name as driver_name,a.order_status_title')
//                 ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
                ->join('ty_users c on a.user_id=c.user_id', 'LEFT')
                ->join('ty_store d on a.store_id=d.store_id', 'LEFT')
                ->join('ty_users e on a.driver_id=e.user_id','LEFT')
                ->where('a.user_id=' . $v['user_id'] . '  and a.driver_id > 0 and a.order_status<3 and a.shipping_status=1 and a.pda_qdzt=0 and a.ruku_count > 0 and a.ruku_count = a.jian_count and a.chuku_count = a.ruku_count and a.ruku_last_time is not null and a.chuku_last_time is not null' . $myw )
                ->order($order2)
                // ->limit(10)
                ->select(); //过滤获取主订单

            $xiaoji = 0;
            foreach ($order_list as $keys => $values) { //整理子单
                $rukunum = $values['ruku_count'];
                $chukunum = $values['chuku_count'];
                $order_list[$keys]['ruku'] = $rukunum;
                $order_list[$keys]['chuku'] = $chukunum;
                $order_list[$keys]['order_amount'] = sanwei($values['total_amount']+$values['yijia_heji']);
                $order_list[$keys]['coupon_price'] = sanwei($values['coupon_price']);
                $xiaoji += sanwei($values['order_amount']+$values['yijia_heji']);
                $zongji+=$values['order_amount']+$values['yijia_heji'];
            }
            $orderList[$key]["xiaoji"] = $xiaoji;
            $orderList[$key]["order_list"] = $order_list;
        }
        // dump($orderList);
        //echo json_encode($orderList);
        $store_list = M('store')->getField('store_id,store_name');
        $this->assign('store_list',$store_list);
        $this->assign('show',$Page->show());
        $this->assign('list',$orderList);
        $this->assign('heji_price',round($heji_price,2));
        $this->assign('order_count',$order_count);
        $this->assign('sum_price',round($sum_price,2));
        $this->assign('coupon_price',$coupon_price);
        C('TOKEN_ON',false);
        $this->display();
    }



    public function pda_new2(){
        $condition = array();$myw=' ';
        I('kehu') ? $condition['c.company'] = array('like','%'.trim(I('kehu')).'%') : false;
        I('shanghu') ? $condition['d.store_name'] = array('like','%'.trim(I('shanghu')).'%') : false;
        $action=$_POST['action'];$master_order_sn=$_POST['master_order_sn'];$str=$_POST['str'];
        $pda_open=tpCache("basic")['pda_open'];


        if(!empty($action) && !empty($master_order_sn)){
            if($pda_open==0){
                echo '1';exit;
            }
            $order_ids = M('order')->where(['master_order_sn'=>$master_order_sn,'order_status'=>['in','1,2']])->getField('order_id,store_id');
            $ids = '';
                foreach ($order_ids as $key=>$item){
                    $order_id = $key;
                    $store_id = $item;
                    $ids .= $order_id.',';
                    //更新产品销量
                    $order_list=M("order_goods")->field('goods_id,goods_num')->where('order_id='.$order_id)->select();
                    foreach($order_list as $v){
                        $order_list = M('order')->field('ufenbu_id')->where(['order_id'=>$order_id])->find();
                        if(empty($order_list['ufenbu_id'])){
                            M('goods')->where('goods_id='.$v['goods_id'])->setInc('sales_sum',(int)$v['goods_num']);
                        }else{
                            $fenbu_goods = M('fenbu_goods')->where('goods_id='.$v['goods_id'])->find();
                            if(!empty($fenbu_goods)){
                                M('fenbu_goods')->where(['goods_id'=>$v['goods_id'],'fenbu_id'=>$order_list['ufenbu_id']])->setInc('sales_sum',(int)$v['goods_num']);
                            }else{
                                M('fenbu_goods')->add(['goods_id'=>$v['goods_id'],'fenbu_id'=>$order_list['ufenbu_id'],'sales_sum'=>(int)$v['goods_num']]);
                            }
                        }
                        
                    }

                    //溢价状态
                    M("order_yijia")->where('order_id='.$order_id)->setField('yijia_status','1');

                    M("order")->where('order_id='.$order_id)->save([
                        'order_status'=>'2',
                        'pay_status'=>'1',
                        'pda_checkout'=>'1',
                        'is_checkout'=>1
                    ]);// 标识为已经结算
                    //开始结算

                    $list = M('order')->where('order_id='.$order_id)->find();
                    $order_statis = M('order_statis')->where(['order_sn'=>$list['order_sn']])->find();
                    if($order_statis){
                        continue;
                    } // 没有数据直接跳出
                    $data = array(
                        'start_date' => time(), // 结算时间
                        'end_date'   => time(), // 结算截止时间
                        'create_date'=>  time(), // 记录创建时间
                        'store_id'   => $store_id, // 店铺id
                    );
                    if($list['coupon_id'] != 0){
                        $couponStore_id = M('coupon')->where(['id'=>$list['coupon_id']])->getField('store_id');
                        if($couponStore_id > 0){
                            $list['total_amount'] = $list['order_amount'];
                        }
                    }
                    $order_goods = M('order_goods')->where(array('order_id' => $order_id))->select();//订单商品列表
                    $commis_totals=0;

                    if($list['dai_type']==2){
                        $commis_totals=$number=$list['total_amount']*$order_goods[0]['points']/100;
                        //$number *= -1;
                    }else{
                        foreach($order_goods as $vss){
                            $commis_totals+=$vss['points']*$vss['member_goods_price']*$vss['goods_num']/100;
                        }
                    }
                    if($list['shi_price']>0)
                        $list['total_amount']=$list['shi_price'];

                    $data['result_totals'] =$list['total_amount']-sanwei($commis_totals); //+$list['integral_money'];// 本期应结

                    $data['order_sn'] = $list['order_sn'];// 订单商品金额
                    $data['order_totals'] =$list['total_amount'];// 订单商品金额
                    $data['shipping_totals'] = $list['shipping_price'];// 运费
                    $data['commis_totals'] =  \sanwei($commis_totals);// 平台费用
                    $data['discount_totals'] =  $list['discount'];// 改单价

                    //M('order')->where("order_id =".$list['order_id'])->save(array('is_checkout' =>1)); // 标识为已经结算

                    M('order_statis')->add($data); // 添加一笔结算统计
                    M('users_price')->where('order_id='.$order_id)->setField(['status'=>2]);
                    // 给商家加钱 记录日志
                    storeAccountLog($store_id,$data['result_totals'],$data['result_totals'] * -1,'平台订单结算');
                    //开始计算积分
                    accountLog($list['user_id'],0,$list['total_amount'],'订单 '.$list['order_sn'].' 赠送的积分！',0,$list['order_id']);

                 }
                 adminLog('new确认收款'.$ids);
                exit;
            }



        $shoukuan=I('shoukuan');
        $order1 = 'c.xsort asc';

        if(I('master_order_sn') ){
            $subQuery_orderIds = M()->query('select order_id from ty_order WHERE LOCATE('.I('master_order_sn').',master_order_sn) > 0');

            foreach ($subQuery_orderIds as $item){
                $ids[] = $item['order_id'];
            }
            if($ids){
                $condition['a.order_id'] = ['in',join(',',$ids)];
            }else{
                $condition['a.order_id'] = 0;
            }

        }

        if(I('order_sn') ){
            $subQuery_orderIds = M()->query('select order_id from ty_order WHERE LOCATE('.I('order_sn').',order_sn) > 0');

            foreach ($subQuery_orderIds as $item){
                $ids[] = $item['order_id'];
            }
            if($ids){
                $condition['a.order_id'] = ['in',join(',',$ids)];
            }else{
                $condition['a.order_id'] = 0;
            }

        }


        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        I('biaoshi_xian') && $condition['c.biaoshi_xian'] = I('biaoshi_xian');
        $order_status_title = I('order_status_title');

        if($order_status_title == 1 ){
            $condition['a.order_status_title'] = 0;
            $myw .= ' and a.order_status_title = 0';
        }elseif($order_status_title == 2 ){
            $condition['a.order_status_title'] = 1;
            $myw .= ' and a.order_status_title = 1';
        }elseif($order_status_title == 3 ){
            $condition['a.order_status_title'] = 2;
            $myw .= ' and a.order_status_title = 2';
        }


        $condition['a.order_status'] = ['lt',3];//判断要列出的订单状态
        $condition['a.ruku_count'] = ['gt',0];
        $condition['a.chuku_count'] = ['gt',0];
        $condition['_string'] = '(a.ruku_count = a.jian_count and a.chuku_count = a.ruku_count and a.ruku_last_time is not null and a.chuku_last_time is not null and a.driver_id > 0)';

        if(I('driver')){
            $condition['e.nick_name'] = I('driver');
            $myw.=' and e.nick_name = "'.I('driver').'" ';
        }

        if($shoukuan!=""){
            $condition['a.pda_checkout'] = $shoukuan;
            $condition['a.is_checkout'] = $shoukuan;
            $myw.=' and a.pda_checkout = "'.$shoukuan.'" ';
            $myw.=' and a.is_checkout = "'.$shoukuan.'" ';
        }

        if(I('duizhang_sn')){
            $orderIds = M('pda_duizhang')->where(['duizhang_sn'=>I('duizhang_sn')])->getField('order_ids');
            if($orderIds){
                $orderIds = json_decode($orderIds,true);
                $condition['a.order_id'] = ['in',join(',',$orderIds)];
                $myw.=' and a.order_id in ('.join(',',$orderIds).') ';
                $order1 = 'field(a.order_id,'.join(',',$orderIds).')';
            }

        }else{
            if($this->begin && $this->end){
                $condition['a.chuku_last_time'] = array('between',"$this->begin,$this->end");
                $myw.=' and a.chuku_last_time > "'.$this->begin.' " and  a.chuku_last_time < "'.$this->end.'" ' ;
            }
        }

        if(I('tag')){
            if(I('tag') == 1){
                $condition['a.tag_price'] = ['eq',0];
                $myw.=" AND a.tag_price = 0 ";
            }else{
                $condition['a.tag_price'] = ['neq',0];
                $myw.=" AND a.tag_price <> 0 ";
            }
        }

        $heji_price =$sum_price =$coupon_price=$order_count=$change=0;
        $param = I('');
        unset($param['timegap']);
        $param_status = 0;
        foreach ($param as $ii){
            if($ii){
                $param_status = 1;
            }
        }

        if($param_status){
            $count = M('order a')
                ->field('a.user_id,SUM(a.order_amount+yijia_heji) as total_amount,SUM(a.order_amount+yijia_heji) as order_amount,SUM(coupon_price) as coupon_price')
                ->join('ty_users c on a.user_id=c.user_id','LEFT')
                ->join('ty_store d on a.store_id=d.store_id','LEFT')
                ->join('ty_users e on a.driver_id=e.user_id','LEFT')
                ->where($condition)->order('a.order_id desc')->group('a.master_order_sn')
                ->select();
        }else{
            $count = M('order a')
                ->field('a.user_id,SUM(a.order_amount+yijia_heji) as total_amount,SUM(a.order_amount+yijia_heji) as order_amount,SUM(coupon_price) as coupon_price')
                ->where($condition)->order('a.order_id desc')->group('a.master_order_sn')
                ->select();
        }

        // dump($condition);


        foreach ($count as $item){
            $heji_price += $item['order_amount'];
            $sum_price += $item['total_amount'];
            $coupon_price += $item['coupon_price'];
        }
        $order_count = count($count);

        // dump($condition);

        $Page  = new Page2(count($count), $_GET['num']);



        //获取订单列表
        $orderList = M('order a')
            ->field('a.is_checkout,a.order_id,a.order_status_title,a.user_id,c.nickname,c.company, c.biaoshi_xian,e.nick_name as driver_name,a.order_status_title,SUM(order_amount) as order_amount,a.master_order_sn,COUNT(*) as count')
//             ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->join('ty_users e on a.driver_id=e.user_id','LEFT')
            ->where($condition)
            ->limit("$Page->firstRow,$Page->listRows ")
            ->order($order1)
            ->group('a.master_order_sn')->select(); //过滤获取主订单
        
        foreach ($orderList as $k=>$v){
            $change = M('order')->field('change')->where(['master_order_sn'=>$v['master_order_sn']])->select();
            $change_price = 0;
            foreach ($change as $key=>$val){
                $change_price += $val['change'];
            }
            $orderList[$k]['change'] = $change_price;
        }


        //echo json_encode($orderList);
        $store_list = M('store')->getField('store_id,store_name');
        $this->assign('store_list',$store_list);
        $this->assign('show',$Page->show());
        $this->assign('list',$orderList);
        $this->assign('heji_price',round($heji_price,2));
        $this->assign('order_count',$order_count);
        $this->assign('sum_price',round($sum_price,2));
        $this->assign('coupon_price',$coupon_price);
        C('TOKEN_ON',false);
        $this->display();
    }

    public function pda_new3(){
        $condition = array();$myw=' ';
        $action=$_POST['action'];$order_ids=$_POST['datas'];$str=$_POST['str'];
        $shoukuan=I('shoukuan');
        $order1 = 'c.xsort asc';
        $order2 = 'a.order_id desc';
//         $store_name = I('store_name'); $store_ids='';
//         if($store_name)
//         {
//             $store_id_arr = M('store')->where("store_name like '%$store_name%'")->getField('store_id');
//             if($store_id_arr)
//             {
//                 $store_ids="a.store_id=".$store_id_arr;
//
//             }
//         }

        //I('order_sn') ? $condition['order_sn'] =  array('like','%'.trim(I('order_sn')).'%') : false;

        if(I('duizhang_sn') ){
            $orderIds = M('pda_duizhang')->where(['duizhang_sn'=>I('duizhang_sn')])->getField('order_ids');
            if($orderIds){
                $orderIds = json_decode($orderIds,true);
                $condition['a.order_id'] = ['in',join(',',$orderIds)];
                $myw.=' and a.order_id in ('.join(',',$orderIds).') ';
            }

//            $subQuery_orderIds = M()->query('select order_id from ty_order WHERE master_order_sn ='.I('master_order_sn'));
//            foreach ($subQuery_orderIds as $item){
//                $ids[] = $item['order_id'];
//            }
//            if($ids){
//                $myw.=' and a.order_id in ('.join(',',$ids).')';
//            }
        }

        if(I('master_order_sn')){
            $condition['a.master_order_sn'] = ''.I('master_order_sn').'';
            $myw.= "and a.master_order_sn  = '".I('master_order_sn')."' ";
        }





        //echo \json_encode($condition);

        if($action=='yes' && !empty($order_ids)){
            $datas=\explode(',',$order_ids);
            $myorders='';
            foreach($datas as $v){
                $os=\explode('|',$v);
                $order_id=$os[0];
                M("order")->where('order_id='.$order_id)->setField('tag_price',1);
                $myorders.=$order_id.',';
            }
            echo $myorders;exit;
        }elseif($action=='zhuangtai' && !empty($order_ids)){
            $datas=\explode(',',$order_ids);
            $orderIds = [];
            foreach($datas as $v){
                $os=\explode('|',$v);
                $id=$os[0];
                $orderIds[] = $id;
            }
            $order_ids = join(',',$orderIds);
            M("order")->where('order_id in('.$order_ids.')')->setField('pda_qdzt',$str);

            if($str==0){
                M('order')->where('order_id in('.$order_ids.')')
                    ->setField([
                        'order_status'=>1,
                        'shipping_status'=>1,
                        'admin_note'=>null
                    ]);
                M("order_jian")->where('order_id in('.$order_ids.')')->setField([
                    'pda_name_ruku'=>'ddt_01',
                    'pda_name_chuku'=>'ddt_01',
                    'ruku_time'=>strtotime(date("Y-m-d H:i:s")),
                    'chuku_time'=>strtotime(date("Y-m-d H:i:s")),
                    'status_r'=>1,
                    'status_c'=>1
                ]);

            }elseif($str==1){
                foreach ($orderIds as $orid){
                    $pdzt_order = M('order')->where(['order_id'=>$orid])->find();
                    M('order')->where(['order_id'=>$orid])->save([
                        'pda_qdzt'=>1,
//                        'order_status'=>1,
//                        'shipping_status'=>1,
//                        'chuku_count'=>0,
//                        'chuku_last_time'=>null,
                        'admin_note'=>'缺货 入库时间：'.date('Y-m-d H:i',$pdzt_order['ruku_last_time']).' 出库时间：'.date('Y-m-d H:i',$pdzt_order['chuku_last_time'])
                    ]);
                }

//                 M('order')->where('order_id in('.$order_ids.')')
//                     ->setField();

//                M("order_jian")->where('order_id in('.$order_ids.')')->setField([
//                    'pda_name_chuku'=>null,
//                    'chuku_time'=>null,
//                    'status_c'=>0
//                ]);
            }elseif($str==2){
                $ciri = M('order')->where('order_id in('.$order_ids.')')->select();
                foreach ($ciri as $item){
                    $ruku_last_time = strtotime(date('Y-m-d H:i',strtotime('+1 day',$item['ruku_last_time']))); //次日送入库时间增加一天
                    M('order')->where(['order_id'=>$item['order_id']])->setField([
                        'admin_note'=>'次日送订单',
                        'chuku_count'=>0,
                        'chuku_last_time'=>null,
                        'pda_qdzt'=>2,
                        'ruku_last_time'=>$ruku_last_time
                    ]);

                    M("order_jian")->where(['order_id'=>$item['order_id']])->setField([
                        'ruku_time'=>$ruku_last_time,
                        'pda_name_chuku'=>null,
                        'chuku_time'=>null,
                        'status_c'=>0
                    ]);
                }



            }
            echo 1;exit;
        }

        $heji_price =$sum_price =$coupon_price=$order_count=0;
        // dump($condition);
        $count = M('order a')
            ->field('a.master_order_sn,a.user_id,SUM(a.total_amount+yijia_heji) as total_amount,SUM(order_amount+yijia_heji) as order_amount,SUM(coupon_price) as coupon_price')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->join('ty_users e on a.driver_id=e.user_id','LEFT')
            ->where($condition)->order('a.order_id desc')->group('a.master_order_sn')
            ->select();

        foreach ($count as $item){
            $heji_price += $item['order_amount'];
            $sum_price += $item['total_amount'];
            $coupon_price += $item['coupon_price'];
        }
        $order_count = count($count);

        // dump($condition);

        $Page  = new Page2(count($count), $_GET['num']);

        //获取订单列表
        $orderList = M('order a')
            ->field('a.master_order_sn,a.order_id,a.user_id,c.nickname,c.company, c.biaoshi_xian,e.nick_name as driver_name,a.order_status_title')
//             ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->join('ty_users e on a.driver_id=e.user_id','LEFT')
            ->where($condition)
            ->limit("$Page->firstRow,$Page->listRows ")
            ->order($order1)->group('a.master_order_sn')
            ->select(); //过滤获取主订单



        foreach($orderList as $key=>$v) { //整理子单
            $order_list = M('order a')
                ->field('a.ruku_last_time,a.chuku_last_time,a.order_id,a.order_sn,a.store_id,a.jian_count,a.order_amount,a.tag_price,c.nickname,c.company,d.store_name,c.biaoshi_xian,a.ruku_count,a.chuku_count,a.is_checkout,a.admin_note,a.yijia_heji,a.coupon_price,a.total_amount,e.nick_name as driver_name,a.order_status_title,a.change')
//                 ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
                ->join('ty_users c on a.user_id=c.user_id', 'LEFT')
                ->join('ty_store d on a.store_id=d.store_id', 'LEFT')
                ->join('ty_users e on a.driver_id=e.user_id','LEFT')
                ->where('a.driver_id > 0 and a.order_status<3 and a.shipping_status=1 and a.pda_qdzt=0 and a.ruku_count > 0 and a.ruku_count = a.jian_count and a.chuku_count = a.ruku_count and a.ruku_last_time is not null and a.chuku_last_time is not null' . $myw )
                ->order($order2)
                // ->limit(10)
                ->select(); //过滤获取主订单

            $xiaoji = 0;
            foreach ($order_list as $keys => $values) { //整理子单
                $rukunum = $values['ruku_count'];
                $chukunum = $values['chuku_count'];
                $order_list[$keys]['ruku'] = $rukunum;
                $order_list[$keys]['chuku'] = $chukunum;
                $order_list[$keys]['order_amount'] = sanwei($values['total_amount']+$values['yijia_heji']);
                $order_list[$keys]['coupon_price'] = sanwei($values['coupon_price']);
                $xiaoji += sanwei($values['order_amount']+$values['yijia_heji']);
                $zongji+=$values['order_amount']+$values['yijia_heji'];
            }
            $orderList[$key]["xiaoji"] = $xiaoji;
            $orderList[$key]["order_list"] = $order_list;
        }
        // dump($orderList);
        //echo json_encode($orderList);
        $store_list = M('store')->getField('store_id,store_name');
        $this->assign('store_list',$store_list);
        $this->assign('show',$Page->show());
        $this->assign('list',$orderList);
        $this->assign('heji_price',$heji_price);
        $this->assign('order_count',$order_count);
        $this->assign('sum_price',$sum_price);
        $this->assign('coupon_price',$coupon_price);
        C('TOKEN_ON',false);
        $this->display();
    }



    /**
     * 导出配送单对账数据
     */
    public function export_pdaqd2()
    {

        $condition = array();$myw=' ';
        I('kehu') ? $condition['c.company'] = array('like','%'.trim(I('kehu')).'%') : false;
        I('shanghu') ? $condition['d.store_name'] = array('like','%'.trim(I('shanghu')).'%') : false;
        $action=$_POST['action'];$order_ids=$_POST['datas'];$str=$_POST['str'];
        $i = 1;
        $shoukuan=I('shoukuan');
        $order1 = 'c.xsort asc';
        $order2 = 'a.order_id desc';
//         $store_name = I('store_name'); $store_ids='';
//         if($store_name)
//         {
//             $store_id_arr = M('store')->where("store_name like '%$store_name%'")->getField('store_id');
//             if($store_id_arr)
//             {
//                 $store_ids="a.store_id=".$store_id_arr;
//
//             }
//         }

        //I('order_sn') ? $condition['order_sn'] =  array('like','%'.trim(I('order_sn')).'%') : false;

        if(I('order_sn') ){
            $subQuery_orderIds = M()->query('select order_id from ty_order WHERE LOCATE('.I('order_sn').',order_sn) > 0');
            foreach ($subQuery_orderIds as $item){
                $ids[] = $item['order_id'];
            }
            if($ids){
                $condition['a.order_id'] = ['in',join(',',$ids)];
            }else{
                $condition['a.order_id'] = 0;
            }

        }
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        I('biaoshi_xian') && $condition['c.biaoshi_xian'] = I('biaoshi_xian');
           $order_status_title = I('order_status_title');
        
            if($order_status_title == 1 ){
                $condition['a.order_status_title'] = 0;
            }elseif($order_status_title == 2 ){
                $condition['a.order_status_title'] = 1;
            }elseif($order_status_title == 3 ){
                $condition['a.order_status_title'] = 2;
            }
        $condition['a.order_status'] = ['lt',3];//判断要列出的订单状态
        $condition['a.shipping_status'] = 1;
        $condition['a.pda_qdzt'] = 0;
        $condition['a.ruku_count'] = ['gt',0];
        $condition['a.chuku_count'] = ['gt',0];
        $condition['_string'] = '(a.ruku_count = a.jian_count and a.chuku_count = a.ruku_count and a.ruku_last_time is not null and a.chuku_last_time is not null and a.driver_id > 0)';

        if(I('driver')){
            $condition['e.nick_name'] = I('driver');
            $myw.=' and e.nick_name = "'.I('driver').'" ';
        }

        if($shoukuan!=""){
            $condition['a.pda_checkout'] = $shoukuan;
            $condition['a.is_checkout'] = $shoukuan;
            $myw.=' and a.pda_checkout = "'.$shoukuan.'" ';
            $myw.=' and a.is_checkout = "'.$shoukuan.'" ';
        }

        if(I('duizhang_sn')){
            $orderIds = M('pda_duizhang')->where(['duizhang_sn'=>I('duizhang_sn')])->getField('order_ids');
            if($orderIds){
                $orderIds = json_decode($orderIds,true);
                $condition['a.order_id'] = ['in',join(',',$orderIds)];
                $myw.=' and a.order_id in ('.join(',',$orderIds).') ';
                $order1 = 'field(a.order_id,'.join(',',$orderIds).')';
                $order2 = 'field(a.order_id,'.join(',',$orderIds).')';
            }

        }else{
            if($this->begin && $this->end){
                $condition['a.chuku_last_time'] = array('between',"$this->begin,$this->end");
                $myw.=' and a.chuku_last_time > "'.$this->begin.' " and  a.chuku_last_time < "'.$this->end.'" ' ;
            }
        }

        if(I('tag')){
            if(I('tag') == 1){
                $condition['a.tag_price'] = ['eq',0];
                $myw.=" AND a.tag_price = 0 ";
            }else{
                $condition['a.tag_price'] = ['neq',0];
                $myw.=" AND a.tag_price <> 0 ";
            }
        }



        //获取订单列表
        $orderList = M('order a')
            ->field('a.order_id,a.pda_checkout,a.user_id,c.nickname,c.company, c.biaoshi_xian,e.nick_name as driver_name')
//             ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->join('ty_users e on a.driver_id=e.user_id','LEFT')
            ->where($condition)
            ->order($order1)
            ->group('a.user_id')->select(); //过滤获取主订单

        // foreach($orderList as $v){
        // 	$user_ids.=$v['user_id'].',';
        // }
        // $user_ids=\rtrim($user_ids,',');


        foreach($orderList as $key=>$v) { //整理子单
            $order_list = M('order a')
                ->field('a.order_id,a.order_sn,a.pda_checkout,a.store_id,a.jian_count,a.order_amount,a.tag_price,c.nickname,c.company,d.store_name,c.biaoshi_xian,a.ruku_count,a.chuku_count,a.is_checkout,a.admin_note,a.yijia_heji,a.coupon_price,a.total_amount,e.nick_name as driver_name')
//                 ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
                ->join('ty_users c on a.user_id=c.user_id', 'LEFT')
                ->join('ty_store d on a.store_id=d.store_id', 'LEFT')
                ->join('ty_users e on a.driver_id=e.user_id','LEFT')
                ->where('a.user_id=' . $v['user_id'] . ' and a.driver_id > 0 and a.order_status<3 and a.shipping_status=1 and a.pda_qdzt=0 and a.ruku_count > 0 and a.ruku_count = a.jian_count and a.chuku_count = a.ruku_count and a.ruku_last_time is not null and a.chuku_last_time is not null' . $myw)

                ->order($order2)
                ->select(); //过滤获取主订单

            $xiaoji = 0;
            foreach ($order_list as $keys => $values) { //整理子单
                $rukunum = $values['ruku_count'];
                $chukunum = $values['chuku_count'];
                $order_list[$keys]['ruku'] = $rukunum;
                $order_list[$keys]['chuku'] = $chukunum;
                $order_list[$keys]['order_amount'] = sanwei($values['order_amount']+$values['yijia_heji']);
                $order_list[$keys]['coupon_price'] = sanwei($values['coupon_price']);
                $xiaoji += sanwei($values['order_amount']+$values['yijia_heji']);
                $zongji+=$values['order_amount']+$values['yijia_heji'];
            }
            $orderList[$key]["xiaoji"] = $xiaoji;
            $orderList[$key]["order_list"] = $order_list;
        }




        $strTable ='<table style="width:210mm;table-layout:fixed" border="1">';
        $strTable .= '<tr style="font-weight:bold">';
        $strTable .= '<td colspan="3" style="height:35px;">日期：'.date('Y',time()).'年'.date('m',time()).'月'.date('d',time()).'日'.date('H',time()).':'.date('i',time()).'</td>';
        $strTable .= '<td colspan="3">姓名：  </td>';
        $strTable .= '<td colspan="2">车牌：  </td>';
        $strTable .= '<td colspan="4">线路：  </td>';
        $strTable .= '</tr>';
        $strTable .= '<tr style="font-weight:bold">';
        $strTable .= '<td style="height:35px;text-align:center">&nbsp;配送总金额&nbsp;</td>';
        $strTable .= '<td style="width:40px;text-align:center;word-break:break-all;">扫码支付</td>';
        $strTable .= '<td colspan="4" style="text-align:center">现金</td>';
//         $strTable .= '<td colspan="2" style="text-align:center"></td>';
        $strTable .= '<td colspan="6" style="text-align:center">未配送金额</td>';
        //$strTable .= '<td colspan="2">&nbsp;&nbsp;</td>';
        $strTable .= '</tr>';
        $strTable .= '<tr>';
        $strTable .= '<td style="height:35px"></td>';
        $strTable .= '<td></td>';
        $strTable .= '<td colspan="4"></td>';
//         $strTable .= '<td colspan="2"></td>';
        $strTable .= '<td colspan="6"></td>';
        //$strTable .= '<td colspan="2"></td>';
        $strTable .= '</tr>';
        $strTable .= '<tr style="font-weight:bold">';
        $strTable .= '<td style="text-align:center;font-size:12px;width:95px;height:35px;">序号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:40px;">客户名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:72px;">订单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:52px;">件数</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:105px;">商家名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:38px;">线路</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:65px;">小计金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:65px;">合计金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:50px;">现金</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:50px;">扫码支付</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:50px;">物流状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:50px;">回款状态</td>';
        $strTable .= '</tr>';
        foreach($orderList as $vs){
            $strTables='';$i++;$tuihuo=0;$strTables2='';
            $xiaoji2=0;
            foreach($vs['order_list'] as $vss){
                // $tuilist=M('return_goods')->where('order_id='.$vss['order_id'])->select();
                // foreach($tuilist as $tv){
                // 	$tuihuo+=\sanwei($tv['member_goods_price']*$tv['goods_num']);
                // }
                $xiaoji2 += ($vss['order_amount']);
                // $zongji2+=$vss['order_amount']+$vss['yijia_heji'];
                $fast_text = '';
                if($vss['fast_flag']){
                    $fast_text = "快";
                }

                $strTables .= '<tr>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.substr($vss['order_sn'],-7).'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.$vss['driver_name'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.$vss['chuku'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.$vss['store_name'].'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px">'.$vss['biaoshi_xian'].' '.$fast_text.'</td>';
                $strTables .= '<td style="text-align:center;font-size:12px;height:35px;color:red">'.($vss['order_amount']).'</td>';
                $strTables .= '</tr>';

                $strTables2 .= '<tr>';
                $strTables2 .= '<td style="text-align:center;font-size:12px;height:35px"></td>';
                $strTables2 .= '<td style="text-align:center;font-size:12px;height:35px"></td>';
                $strTables2 .= '<td style="text-align:center;font-size:12px;height:35px"></td>';
               
                
                if($vss['pda_checkout'] == 1 && $vss['is_checkout'] == 1){
                    $strTables2 .= '<td style="text-align:center;font-size:12px;height:35px">已支付</td>';
                }else{
                    $strTables2 .= '<td style="text-align:center;font-size:12px;height:35px">未支付</td>';
                }
                // if($vss['tag_price']){
                //     $strTables2 .= '<td style="text-align:center;font-size:12px;height:35px">已回款/'.$title.'</td>';
                // }else{
                //     $strTables2 .= '<td style="text-align:center;font-size:12px;height:35px">未回款/'.$title.'</td>';
                // }
                $strTables2 .= '</tr>';
            }

            $strTable .= '<tr style="border:1px solid #000">
		<td style="text-align:center;font-size:12px;border:1px;width:50px;">'.$i.'</td>
		<td style="text-align:center;font-size:12px;border:1px;width:40px;WORD-WRAP:break-all;">'.$vs['company'].'</td>
		<td colspan="5">
		<table width="650" border="1">
		'.$strTables.'
		</table>
		</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold">'.($vs['xiaoji']) .'</td>
	    <td colspan="4">
		<table width="650" border="1">
		'.$strTables2.'
		</table>
		</td>
		</tr>';
        }

        $strTable .= '<tr style="border:1px solid #000">
		<td colspan="6" style="text-align:right;font-weight:bold;height:32px">
		合计：
		</td>
		<td style="text-align:center;font-size:12px;color:red;font-weight:bold">'.$zongji.'</td>
		</tr>';
        $strTable .='</table>';

        unset($orderList);
        downloadExcel($strTable,'order');
        exit();

    }


    /**
     * 导出配送单对账数据
     */
    public function export_pdaqd()
    {
        $condition = array();$myw=' ';
        I('kehu') ? $condition['c.company'] = array('like','%'.trim(I('kehu')).'%') : false;
        I('shanghu') ? $condition['d.store_name'] = array('like','%'.trim(I('shanghu')).'%') : false;
        $action=$_POST['action'];$order_ids=$_POST['datas'];$str=$_POST['str'];
        $i = 1;
        $shoukuan=I('shoukuan');
        $order1 = 'c.xsort asc';
        $order2 = 'a.order_id desc';

        if(I('order_sn') ){
            $subQuery_orderIds = M()->query('select order_id from ty_order WHERE LOCATE('.I('order_sn').',order_sn) > 0');
            foreach ($subQuery_orderIds as $item){
                $ids[] = $item['order_id'];
            }
            if($ids){
                $condition['a.order_id'] = ['in',join(',',$ids)];
                $myw .= ' and a.order_id in ('.join(',',$ids).')';
            }else{
                $condition['a.order_id'] = 0;
            }

        }
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        I('biaoshi_xian') && $condition['c.biaoshi_xian'] = I('biaoshi_xian');
        $order_status_title = I('order_status_title');

        if($order_status_title == 1 ){
            $condition['a.order_status_title'] = 0;
        }elseif($order_status_title == 2 ){
            $condition['a.order_status_title'] = 1;
        }elseif($order_status_title == 3 ){
            $condition['a.order_status_title'] = 2;
        }
        $condition['a.order_status'] = ['lt',3];//判断要列出的订单状态
        $condition['a.shipping_status'] = 1;
        $condition['a.pda_qdzt'] = 0;
        $condition['a.ruku_count'] = ['gt',0];
        $condition['a.chuku_count'] = ['gt',0];
        $condition['_string'] = '(a.ruku_count = a.jian_count and a.chuku_count = a.ruku_count and a.ruku_last_time is not null and a.chuku_last_time is not null and a.driver_id > 0)';

        if(I('driver')){
            $condition['e.nick_name'] = I('driver');
            $myw.=' and e.nick_name = "'.I('driver').'" ';
        }

        if($shoukuan!=""){
            $condition['a.pda_checkout'] = $shoukuan;
            $condition['a.is_checkout'] = $shoukuan;
            $myw.=' and a.pda_checkout = "'.$shoukuan.'" ';
            $myw.=' and a.is_checkout = "'.$shoukuan.'" ';
        }

        if(I('duizhang_sn')){
            $orderIds = M('pda_duizhang')->where(['duizhang_sn'=>I('duizhang_sn')])->getField('order_ids');
            if($orderIds){
                $orderIds = json_decode($orderIds,true);
                $condition['a.order_id'] = ['in',join(',',$orderIds)];
                $myw.=' and a.order_id in ('.join(',',$orderIds).') ';
                $order1 = 'field(a.order_id,'.join(',',$orderIds).')';
                $order2 = 'field(a.order_id,'.join(',',$orderIds).')';
            }

        }else{
            if($this->begin && $this->end){
                $condition['a.chuku_last_time'] = array('between',"$this->begin,$this->end");
                $myw.=' and a.chuku_last_time > "'.$this->begin.' " and  a.chuku_last_time < "'.$this->end.'" ' ;
            }
        }

        if(I('tag')){
            if(I('tag') == 1){
                $condition['a.tag_price'] = ['eq',0];
                $myw.=" AND a.tag_price = 0 ";
            }else{
                $condition['a.tag_price'] = ['neq',0];
                $myw.=" AND a.tag_price <> 0 ";
            }
        }
        
        
        $orderList = M('order a')
            ->field('a.change,a.user_id,a.order_id,a.order_sn,a.pda_checkout,a.store_id,a.jian_count,a.order_amount,a.tag_price,c.nickname,c.company,d.store_name,c.biaoshi_xian,a.ruku_count,a.chuku_count,a.is_checkout,a.admin_note,a.yijia_heji,a.coupon_price,(a.yijia_heji + a.total_amount) as total_amount,e.nick_name as driver_name')
            ->join('ty_users c on a.user_id=c.user_id', 'LEFT')
            ->join('ty_store d on a.store_id=d.store_id', 'LEFT')
            ->join('ty_users e on a.driver_id=e.user_id','LEFT')
            ->where('a.driver_id > 0 and a.order_status<3 and a.shipping_status=1 and a.pda_qdzt=0 and a.ruku_count > 0 and a.ruku_count = a.jian_count and a.chuku_count = a.ruku_count and a.ruku_last_time is not null and a.chuku_last_time is not null' . $myw)
            ->order($order2)
            ->select(); //过滤获取主订单

        $orderList = group_same_key($orderList,'user_id');

        $e_name='联鑫壹天达五金商城';
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Worksheet.Drawing");
        import("Org.Util.PHPExcel.Writer.Excel2007");
        $objPHPExcel = new \PHPExcel();
        $objActSheet = $objPHPExcel->getActiveSheet();

        $objActSheet->setCellValue('A1', '客户名称');
        $objActSheet->setCellValue('B1', '司机');
        $objActSheet->setCellValue('C1', '订单号');
        $objActSheet->setCellValue('D1', '件数');
        $objActSheet->setCellValue('E1', '商家名');
        $objActSheet->setCellValue('F1', '线路');
        $objActSheet->setCellValue('G1', '小计');
        $objActSheet->setCellValue('H1', '合计');
        $objActSheet->setCellValue('I1', '抹零金额');

        $objActSheet->getDefaultRowDimension()->setRowHeight(25);
        $objActSheet->getDefaultColumnDimension()->setWidth(25);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);


        $i=2;
        $datas = [];
        foreach($orderList as $k=>$v){
            $sum = 0;
            foreach ($v as $kk=>$item){
                $sum+=$item['total_amount'];
                $datas[$k]['data'][] = $item;
            }
            $datas[$k]['sum'] = $sum;
        }

        foreach($datas as $v){
            foreach ($v['data'] as $item){
                $objActSheet->setCellValue('A'.$i, $item['company']);
                $objActSheet->setCellValue('B'.$i, $item['driver_name']);
                $objActSheet->setCellValue('C'.$i, ' '.$item['order_sn']);
                $objActSheet->setCellValue('D'.$i, $item['jian_count']);
                $objActSheet->setCellValue('E'.$i, $item['store_name']);
                $objActSheet->setCellValue('F'.$i, $item['biaoshi_xian']);
                $objActSheet->setCellValue('G'.$i, $item['total_amount']);
                $objActSheet->setCellValue('H'.$i, $v['sum']);
                $objActSheet->setCellValue('I'.$i, $item['change']);
                $i++;
            }
        }

        // 设置单元格边框
        $styleThinBlackBorderOutline = array(
            'borders' => array(
                'allborders' => array( //设置全部边框
                    'style' => \PHPExcel_Style_Border::BORDER_THIN //粗的是thick
                ),

            ),
        );

        $objPHPExcel->getActiveSheet()->getStyle( 'A1:H'.($i-1))->applyFromArray($styleThinBlackBorderOutline);

        if($i < 1000000){
            $num2 = 0;
            foreach (array_values($orderList) as $k=>$v) {
                if ($k == 0) {
                    $num1 = 2;
                    $num2 = $num1+count($v)-1;
                }else {
                    $num1 = $num2+1;
                    $num2 = $num1+count($v)-1;
                }

                $objActSheet->mergeCells('A'.$num1.':A'.$num2);//合并单元格
//            $objActSheet->mergeCells('B'.$num1.':B'.$num2);//合并单元格
                $objActSheet->mergeCells('H'.$num1.':H'.$num2);//合并单元格
            }
        }


            ob_end_clean();
            $fileName = $e_name.'对账单';
            $date = date("Y-m-d",time());
            $fileName .= "_{$date}.xlsx";
            //重命名表
            $objPHPExcel->getActiveSheet()->setTitle('viateams');
            //设置活动单指数到第一个表,所以Excel打开这是第一个表
            $objPHPExcel->setActiveSheetIndex(0);
            header('Content-Type: application/vnd.ms-excel');
            header("Content-Disposition: attachment;filename=\"$fileName\"");
            header('Cache-Control: max-age=0');
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');


            ob_start();
            $objWriter->save("php://output");
            $xlsdata = ob_get_contents();
            ob_end_clean();
            $data=['filename' => $fileName, 'file' => "data:application/vnd.ms-excel;base64," . base64_encode($xlsdata)];
            echo json_encode($data);
            exit;
        }

        public function export_pda()
        {
            //搜索条件
            $order_sn = I('order_sn');
            $kehu = I('kehu');
            $shanghu = I('shanghu');
            $timegap = I('timegap');
            $pda = I('pda');
            $pda_open=tpCache("basic")['pda_open'];
            //$where['shipping_status'] =1;
            $biaozhu=$_POST['biaozhu'];
            $tag_price=I('tag_price');
            $order_id=I('order_id');
            $tag=I('tag');
            $shoukuan=I('shoukuan');
            $chuku_time = I('chuku_time');
            $driver=I('driver');
            $wheres="a.order_status <3 ";
            // 搜索条件 STORE_ID
            if(\session('fenbu_id')!=0){
                $wheres.=" and a.ufenbu_id=".\session('fenbu_id');
            }
            $wheres.=" AND a.ruku_last_time > $this->begin AND a.ruku_last_time < $this->end AND a.ruku_last_time != '' AND a.chuku_last_time != '' ";
    //        if($pda){
    //            //$where['pda_name_ruku'] = $pda;
    //            $wheres.=" AND ".$this->z."pda_name_ruku= '$pda' AND ".$this->z."status_r=1 AND a.order_status <> 5 ";
    //        }
            if(!empty($chuku_time)){
                $chuku_time = str_replace('+',' ',$timegap);
                //echo $timegap;
                if($chuku_time){
                    $chuku_timegap = explode(' - ', $chuku_time);
                    $chuku_timebegin = $chuku_timegap[0];
                    $chuku_timeend = $chuku_timegap[1];
                }
                $chukustart = strtotime($chuku_timebegin);
                $chukuend = strtotime($chuku_timeend);//+86399;

                $wheres.=" AND a.chuku_last_time > $chukustart AND a.chuku_last_time < $chukuend ";

            }
            if($tag){
                if($tag == 1){
                    $wheres.=" AND a.tag_price = 0 ";
                }else{
                    $wheres.=" AND a.tag_price <> 0 ";
                }
            }
            if($driver){
                $wheres.=" AND g.nick_name like '%".$driver."%' ";
            }

            if($shoukuan!=""){
                //$where['pda_checkout'] =$shoukuan;
                $wheres.=" AND pda_checkout=$shoukuan ";
            }
            I('biaoshi') && $wheres.=" AND f.biaoshi_xian='".I('biaoshi')."' "; //$where['f.biaoshi_xian'] = I('biaoshi');

            $order_sn && $wheres.=" AND order_sn like '%".$order_sn."%' "; //$where['order_sn'] = array('like','%'.$order_sn.'%');

            $kehu && $wheres.=" AND (f.company like '%".$kehu."%' or a.consignee like '%".$kehu."%') "; //$where['company'] = ['like',"%$kehu%"];
            $shanghu && $wheres.=" AND store_name like '%".$shanghu."%' "; //$where['_string'] = '(store_name like "%'.$shanghu.'%")';
            //获取订单列表
            $list =M()->query("SELECT a.coupon_price,a.chuku_last_time,a.ruku_last_time,a.order_sn,a.pay_status,a.shi_price,a.store_id,a.is_checkout,a.consignee,a.mobile,a.tag_price,a.jian_count,a.dai_type,a.total_amount,a.order_amount,a.yijia_heji,a.order_id,a.discount,d.store_name,a.pda_checkout,a.user_id,a.integral_money,f.biaoshi_xian,g.nick_name as driver_name FROM ty_order a  LEFT JOIN ty_store d on a.store_id=d.store_id LEFT JOIN ty_users f on a.user_id=f.user_id LEFT JOIN ty_users g on a.driver_id=g.user_id WHERE $wheres  ORDER BY a.order_id desc");
            //echo \json_encode($condition);exit;
            $strTable ='<table width="500" border="1">';
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单号</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">司机</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商户名</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">客户名</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单价</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">优惠金额</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">实回款</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台扣点</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="*">线路</td>';
    //        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">在线支付</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="100">应付金额</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="100">包装件数</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="100">入库时间</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="100">状态/标注</td>';
            $strTable .= '</tr>';


            foreach($list as $k=>$val){
                $val['company']=M('users')->where('user_id='.$val['user_id'])->getField('company');
                $val['pprice']=order_price($val['order_id'])['points_count'];
                $val['order_amount']=$val['order_amount']+$val['yijia_heji'];

                if($val['pay_status'] == 1){
                    $val['pay_status'] = '已支付';
                }else{
                    $val['pay_status'] = '未支付';
                }
                if($val['status_c'] == 0){
                    $val['status_c'] = '未出库';
                }else{
                    $val['status_c'] = '已出库';
                }
                if($val['shi_price'] == 0){
                    $yingfu = sanwei($val['order_amount']-$val['pprice']);
                }else{
                    $yingfu = sanwei($val['shi_price']-$val['pprice']);
                }

                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
                $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['driver_name'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['store_name'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['consignee'].'('.$val['company'].')</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['order_amount'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['coupon_price'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['shi_price'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.geshi($val['pprice']).'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;color:red">'.$val['biaoshi_xian'].'</td>';
    //            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['pay_status'].'</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$yingfu.' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['jian_count'].'/件 </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-m-d H:i:s',$val['ruku_last_time']).' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['status_c'].'未回款 </td>';
                $strTable .= '</tr>';
            }
            $strTable .='</table>';
            unset($list);
            downloadExcel($strTable,'pad');
            exit();
        }

        /*
        *旧单收款
        */
    public function financeKuan(){
        $order_id = I('order_id');
        $master = I('master');
        $orderInfo = M('order')->where(['order_id'=>$order_id])->find();
        if($master){
            $orderInfo = M('order')->where(['master_order_sn'=>$order_id])->find();
        }

        $json_arr = [];
        if(!empty($orderInfo)){
            if($master){
                $orderInfo = M('order')->where(['master_order_sn'=>$order_id])->save(['order_status_title'=>2]);
            }else{
                M('order')->where(['order_id'=>$order_id])->save(['order_status_title'=>2]);
            }
            $json_arr['status'] = 1;
            $json_arr['msg'] = '收款成功';
            $json_str = json_encode($json_arr);
        	exit($json_str);
        }else{
            $json_arr['status'] = 0;
            $json_arr['msg'] = '收款失败';
            $json_str = json_encode($json_arr);
        	exit($json_str);
        }
    }
    
    public function export_settlement()
    {
        //搜索条件
        $store_name = I('store_name');
        $account_bank = I('account_bank');
        $store_name && $where['store_name'] = array('like','%'.$store_name.'%');
        $account_bank && $where['account_bank'] = array('like','%'.$account_bank.'%');

        //获取列表

        $list = M("store a"
        )->field('a.*,b.nickname')
            ->join('ty_users b on a.user_id=b.user_id')
            ->order('dz_sort asc')
            ->where($where)
            ->select();	//\print_r(\json_encode($list));

        //echo \json_encode($condition);exit;

        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">店铺id</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">店铺名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">银行名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">银行卡号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">开户名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单金额</td>';
        //$strTable .= '<td style="text-align:center;font-size:12px;" width="*">待结列表金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">待结算资金</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">待退货资金</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">手续费</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">应结算资金</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">注册时间</td>';
        $strTable .= '</tr>';


        foreach($list as $key=>$v){
            $order_price=M('order_statis a')
			//->join('ty_order b on a.order_sn=b.order_sn')
			->where('a.withdrawals_id=0 and a.store_id='.$v['store_id'])->sum('a.order_totals');
            $tuihuo=M('return_goods')->where('store_id='.$v['store_id'].' and status=1')->select();
            //计算退货钱
            $t_hejiprice=0;
            foreach($tuihuo as $vs){
                $t_hejiprice+=$vs['member_goods_price']*$vs['goods_num']*(100-$vs['points'])/100; //商家应该退回的钱
            }

            // $v['commission']=($v['store_money']-$t_hejiprice) * 0.005; //手续费
            $v['commission']=0; //手续费
            $v['tuihuo_price']=$t_hejiprice;
            $v['yingfu_price']=round($v['store_money'] - $t_hejiprice,2); //应付
            // $v['yingfu_price']=round($v['store_money'] - (($v['store_money']-$t_hejiprice) * 0.005) -$t_hejiprice,2); //应付
            $v['order_price']=$order_price;
            //$v['listprice']=M('order_statis')->where('withdrawals_id=0 and store_id='.$v['store_id'])->sum('result_totals');

            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$v['store_id'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">'.$v['store_name'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$v['bank_name'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$v['account_bank'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$v['account_name'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$v['order_price'].'</td>';
            //$strTable .= '<td style="text-align:left;font-size:12px;">'.$v['listprice'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$v['store_money'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.-$v['tuihuo_price'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;color:bule">'.$v['commission'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;color:red">'.$v['yingfu_price'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-d-m H:i:s',$v['store_time']).'</td>';
            $strTable .= '</tr>';
        }
        $strTable .='</table>';
        unset($list);
        downloadExcel($strTable,'结算');
        exit();
    }
	 public function yijia(){
	        $order_sn = I('order_sn');
	 		$goods_name = I('goods_name');
	        $yijia_status = I('yijia_status');
			$fenbu_id = I('fenbu_id');
			
	 			$where['a.add_time']=array(array('gt',$this->begin),array('lt',$this->end));
				$where['c.goods_name'] = array('like','%'.$goods_name.'%');
				if($yijia_status!='') $where['a.yijia_status'] =$yijia_status;
				if($fenbu_id>0)
				$where['a.fenbu_id'] =$fenbu_id;
				
				if(!empty($order_sn))
				$where['a.order_sn'] = array('like','%'.$order_sn.'%');

	 		$count =M('order_yijia a')
					->field('a.*,c.goods_name')
					->join('ty_goods c on a.goods_id=c.goods_id')
					->where($where)
					->select();
	 		foreach($count as $v){
				$y_price=$v['y_price']*$v['goods_num'];
				$s_price=$v['price']*$v['goods_num'];
				
				$ys_price+=$y_price;
				$sj_sprice+=($y_price+$s_price);
				$sy_price+=$s_price;
			}
			
	         $Page  = new Page(count($count),20);
			 $start=$Page->firstRow;
			 $page_size=$Page->listRows;
			 $show  = $Page->show();
	 
	 		$list=M('order_yijia a')
					->field('a.*,c.goods_name')
					->join('ty_goods c on a.goods_id=c.goods_id')
					->where($where)
					->limit("$start,$page_size")
					->order("id desc")
					->select();
	 		foreach($list as $key=>$vs){
	 			$list[$key]['xj_yprice']=$vs['y_price']*$vs['goods_num'];
				$list[$key]['xj_price']=$vs['price']*$vs['goods_num'];
	 		}

	 		$stores=M("store")->getField('store_id,store_name');
	 		$this->assign('stores',$stores);
			$this->assign('fenbu_list',$this->fenbu_list);
			$this->assign('ys_price',$ys_price);$this->assign('sj_sprice',$sj_sprice);$this->assign('sy_price',$sy_price);
	        $this->assign('show',$show);
	        $this->assign('list',$list);
	         C('TOKEN_ON',false);
	         $this->display();
	 	 }
    public function export_yijia()
    {
        //搜索条件
        $order_sn = I('order_sn');
        $goods_name = I('goods_name');
        $yijia_status = I('yijia_status');
        $fenbu_id = I('fenbu_id');

        //获取列表
        $where['a.add_time']=array(array('gt',$this->begin),array('lt',$this->end));
        $where['c.goods_name'] = array('like','%'.$goods_name.'%');
        if($yijia_status!='') $where['a.yijia_status'] =$yijia_status;
        if($fenbu_id>0)
            $where['a.fenbu_id'] =$fenbu_id;

        if(!empty($order_sn))
            $where['a.order_sn'] = array('like','%'.$order_sn.'%');

        $list=M('order_yijia a')
            ->field('a.*,c.goods_name')
            ->join('ty_goods c on a.goods_id=c.goods_id')
            ->where($where)
            ->order("id desc")
            ->select();

        //echo \json_encode($condition);exit;

        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">产品名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商户名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">客户名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">单价</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">数量</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">原小计</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">实收小计</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收益小计</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">下单时间</td>';
        $strTable .= '</tr>';


        foreach($list as $key=>$v){
            $v['xj_yprice']=$v['y_price']*$v['goods_num'];
            $v['xj_price']=$v['price']*$v['goods_num'];
            $stores=M("store")->where(['store_id'=>$v['store_id']])->getField('store_id,store_name');
            $price = $v['xj_yprice']+$v['xj_price'];
            if($v['yijia_status'] == 1){
                $v['yijia_status'] = '已收款';
            }else{
                $v['yijia_status'] = '未收款';
            }
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$v['order_sn'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">'.$v['goods_name'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$stores['store_name'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$v['consignee'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$v['y_price'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$v['goods_num'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$v['xj_yprice'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$price.'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;color:red">'.$v['xj_price'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;color:red">'.$v['yijia_status'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-d-m H:i:s',$v['add_time']).'</td>';
            $strTable .= '</tr>';
        }
        $strTable .='</table>';
        unset($list);
        downloadExcel($strTable,'溢价');
        exit();
    }
     public function pda_duizhang(){
		$id= I('id');
		$store_id=I('store_id');
		$order_sn= I('order_sn');
		$timegap = I('timegap');
		$action = I('action');
		
		if(!empty(session('fenbu_id'))){
			$where="b.fenbu_id=0 and b.ufenbu_id=".session('fenbu_id');
		}else{
            $where = "1";
        }
		
		if($timegap){
			$gap = explode(' - ', $timegap);
			$begin = strtotime($gap[0]);
			$end = strtotime($gap[1]);
			$where .= " and b.ruku_last_time>=$begin and b.ruku_last_time<=$end ";
		}
        $model = M("order_statis a");
		$jiesuan_zt=(int)I('jiesuan_zt');
		!empty($jiesuan_zt) ? $where .= " and a.withdrawals_id>0 " : $where .= " and a.withdrawals_id=0 ";
		
		if($order_sn){
			$where .= " and a.order_sn like '%".$order_sn."%'"; 
		}
		!empty(I('shanghu')) ? $where .= " and c.store_name like '%".I('shanghu')."%'" : false;
		!empty(I('kehu')) ? $where .= " and d.company like '%".I('kehu')."%'" : false;
		//!empty(I('fenbu_id')) ? $where .= " and b.ufenbu_id=".I('fenbu_id') : false;
//echo $where;

        $count = $model
		->field('a.*,b.ruku_last_time,b.order_id,b.yijia_heji,b.jian_count,b.ufenbu_id,d.company,c.store_name')
		->join('ty_order b on a.order_sn=b.order_sn')
		->join('ty_store c on a.store_id=c.store_id')
		->join('ty_users d on b.user_id=d.user_id')
		->where($where)->order("a.id desc")->select();
		//计算合计金额
			$heji=$heji_dd=$heji_kd=0;
			foreach($count as $v){
				$heji_dd+=($v['order_totals']+$v['yijia_heji']);
				$heji_kd+=$v['commis_totals'];
				$heji+=($v['result_totals']+$v['yijia_heji']);
			}

        $Page  = new Page(count($count),100);
        $list = $model
        ->field('a.*,b.ruku_last_time,b.chuku_count,b.order_id,b.yijia_heji,b.jian_count,b.ufenbu_id,d.company,c.store_name')
        ->join('ty_order b on a.order_sn=b.order_sn')
		->join('ty_store c on a.store_id=c.store_id')
        ->join('ty_users d on b.user_id=d.user_id')
        ->where($where)->order("a.id desc")
        ->limit($Page->firstRow.','.$Page->listRows)->select();
		
        if($action=='daochu'){ //导出xls
			$strTable ='<table width="500" border="1">';
			$strTable .= '<tr>';
			$strTable .= '<td style="text-align:center;font-size:12px;width:100px;">订单ID</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;width:150px;">订单号</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;width:130px;">商户名</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;" width="130">客户名</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;" width="130">所属区域</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;" width="120">订单价</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;" width="120">扣点</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;" width="120">应收</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;" width="120">包装件数</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;" width="120">收款时间</td>';
			$strTable .= '</tr>'; 
			
			foreach($count as $val){
				$uquyu=M('fenbu')->where('fenbu_id='.$val['ufenbu_id'])->getField('fenbu_name');
				$zhuangtai=empty($val['chuku_count']) ? '未出库' : '已出库';
				$yingshou=sanwei($val['result_totals']+$val['yijia_heji']);
				
			$strTable .= '<tr>';
				$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_id'].'</td>';
				$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
				$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['store_name'].'</td>';
				$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['company'].'</td>';
				$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$uquyu.'</td>';
				$strTable .= '<td style="text-align:center;font-size:12px;">'.sanwei($val['order_totals']+$val['yijia_heji']).'</td>';
				$strTable .= '<td style="text-align:center;font-size:12px;">'.$val['commis_totals'].'</td>';
			    $strTable .= '<td style="text-align:center;font-size:12px;">'.$yingshou.'</td>';
			    $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['jian_count'].'/件'.$val['company_address'].' </td>';
			    $strTable .= '<td style="text-align:center;font-size:12px;">'.\date('Y-m-d H:i:s',$val['create_date']).'</td>';
				$strTable .= '</tr>'; 
			}
			$strTable .='</table>';
			unset($orderList);
			downloadExcel($strTable,'order');
			exit();
		}
		
        $show  = $Page->show();
		$this->assign([
			'heji'=>$heji,
			'heji_dd'=>$heji_dd,
			'heji_kd'=>$heji_kd
		]);
        $this->assign('show',$show);
        $this->assign('list',$list);
		$this->assign('fenbu_list',$this->fenbu_list);
        $this->display();
	 }
	 
	 public function pdas(){
		$p = I('p',1);
		$start = ($p-1)*20;
		if(session('fenbu_id')!=0){
			$wheres='fenbu_id='.\session('fenbu_id');
		}
		$pda = M('pda')->where($wheres)->limit("$start,20")->select();
		//echo \count(M('order_jian')->where('pda_name_chuku="pda-06"')->group('order_id')->select());
		foreach($pda as $key=>$v){
			$orders=M('order_jian')
			->where($this->z."chuku_time>$this->begin and ".$this->z."chuku_time<$this->end and ".$this->z."pda_name_chuku='".$v['pda_name']."'")->group('order_id')
			->select();
			
			$pda[$key]['danshu']=count($orders); //单数
			//
			//销售额
			$price=0;
			$ids='';
			foreach($orders as $vs){
				$ids.=$vs['order_id'].',';
				$data=M('order')
                    ->field('total_amount,yijia_heji')
                    ->where('order_id='.$vs['order_id'].' and order_status in(0,1,2,4)')
                    ->find();
                $price+=$data['total_amount']+$data['yijia_heji'];
			}

			$ids=rtrim($ids, ",");
			if($ids){
				$zorder=M('order a')
				->field('a.*')
				->where('a.order_id in('.$ids.') and a.order_status in(0,1,2,4)')->select();
                foreach ($zorder as $k=>$v){
                    $zorder[$k]['tongji'] = $v['total_amount']+$v['yijia_heji'];
                }
				$pda[$key]['zorder']=$zorder;
			}
			
			$pda[$key]['jine']=$price;
			
		}

		//echo \json_encode($pda);exit;
		$pda= arraySort($pda,'jine', SORT_DESC);
		$this->assign([
			'list'=>$pda,
			'begin'=>$this->begin,
			'end'=>$this->end
		]);
		
		$total = M('pda')->where($wheres)->count();
		$count =  $total;
		$Page = new \Think\Page($count,20);
		$show = $Page->show();
		$this->assign('page',$show);
		
        $this->assign('brandList',$brandList);
		$this->display();
	 }

     public function noruku_pda(){ //入库未出库pda 
     
        $fenbu = M('fenbu')->field('fenbu_id,fenbu_name')->select();
        $ids = '';
        foreach ($fenbu as $v){
            $ids.= $v['fenbu_id'].',';
        }
        $ids = substr($ids,0,-1);
		$fenbu_id=I('fenbu_id') !== '' ? I('fenbu_id') : '';
		$fenbu_ids=$fenbu_id !== '' ? $fenbu_id : $ids;
     
        $order_sn = I('order_sn');
		$kehu = I('kehu');
        $timegap = I('timegap');
		$pda = I('pda');
// 		$where="a.".$this->z."status_r=1 and a.".$this->z."status_c=0 and b.ufenbu_id=".\session('fenbu_id');
		$where="a.".$this->z."status_r=1 and a.".$this->z."status_c=0 and b.ufenbu_id in ('$fenbu_ids') ";
		
			$where.=" and a.".$this->z."ruku_time>$this->begin and a.".$this->z."ruku_time<$this->end";
			//if($timegap)
			//$where['a.chuku_time']=array(array('gt',$this->begin),array('lt',$this->end));
			
		if($order_sn)
			$where.=" and b.order_sn like'%".$order_sn."%'";
		if($pda)
			$where.=" and pda_name_ruku='".$pda."'";
		if($kehu)
			$where.=" and (b.consignee like'%".$kehu."%' or c.store_name like'%".$kehu."%')";
	
		$count = M("order_jian a")
		->join('ty_order b on a.order_id=b.order_id')
		->join('ty_store c on b.store_id=c.store_id','LEFT')->order('a.id desc')->group('a.order_id')
		->where($where)
		->select();
		
        $Page  = new Page(count($count),20);
		
		$list = M("order_jian a")
		->join('ty_order b on a.order_id=b.order_id')
		->join('ty_store c on b.store_id=c.store_id','LEFT')->order('a.id desc')->group('a.order_id')
		->where($where)
		->limit($Page->firstRow.','.$Page->listRows)
		->select();

	    $dprice=0;
		foreach($list as $key=>$v){
			$order_id=$v['order_id']?$v['order_id']:0;
			$list[$key]['ruku_num']=M('order_jian')->where('order_id='.$order_id)->count(); //入库数
		}
		
		foreach($count as $v){
			$dprice+=$v['order_amount'];
		}
		$this->assign('dprice',$dprice);

        $this->assign('create_time',$create_time2);
        $show  = $Page->show();
// 		$this->assign('pda_list',M("pda")->where('fenbu_id='.\session('fenbu_id'))->select());
		$this->assign('pda_list',M("pda")->where("fenbu_id in ('$fenbu_ids')")->select());
        $this->assign('show',$show);
        $this->assign('list',$list);
        // dump($fenbu);
        $this->assign('fenbu_list',$fenbu);
        C('TOKEN_ON',false);
        $this->display();
	 }
	 
     public function nochuku_pda(){ //出库未入库pda 
        $order_sn = I('order_sn');
		$kehu = I('kehu');
        $timegap = I('timegap');
		$pda = I('pda');
		$where="a.".$this->z."status_r=0 and a.".$this->z."status_c=1 and b.ufenbu_id=".\session('fenbu_id');
		
        if($timegap)
			$where.=" and a.".$this->z."ruku_time>$this->begin and a.".$this->z."ruku_time<$this->end";
			//$where['a.chuku_time']=array(array('gt',$this->begin),array('lt',$this->end));
		if($order_sn)
			$where.=" and b.order_sn like'%".$order_sn."%'";
		if($pda)
			$where.=" and ".$this->z."pda_name_ruku='".$pda."'";
		if($kehu)
			$where.=" and (b.consignee like'%".$kehu."%' or c.store_name like'%".$kehu."%')";
	
		$count = M("order_jian a")
		->join('ty_order b on a.order_id=b.order_id')
		->join('ty_store c on b.store_id=c.store_id','LEFT')->order('a.id desc')->group('a.order_id')
		->where($where)
		->select();
		
        $Page  = new Page(count($count),20);
		
		$list = M("order_jian a")
		->join('ty_order b on a.order_id=b.order_id')
		->join('ty_store c on b.store_id=c.store_id','LEFT')->order('a.id desc')->group('a.order_id')
		->where($where)
		->limit($Page->firstRow.','.$Page->listRows)
		->select();

	$dprice=0;
		foreach($list as $key=>$v){
			$order_id=$v['order_id']?$v['order_id']:0;
			$list[$key][$this->z.'chu_num']=M('order_jian')->where('order_id='.$order_id)->count(); //出库数
		}
		
		foreach($count as $v){
			$dprice+=$v['order_amount'];
		}
		$this->assign('dprice',$dprice);

        $this->assign('create_time',$create_time2);
        $show  = $Page->show();
		$this->assign('pda_list',M("pda")->where('fenbu_id='.\session('fenbu_id'))->select());
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();
	 }
	 
    public function export_ruku()
    {
    	//搜索条件
        $order_sn = I('order_sn');
        $kehu = I('kehu');
        $biaoshi = I('biaoshi');
        $where="b.order_status < 3 and b.shipping_status = 1 and b.jian_count > 0 and b.jian_count = b.ruku_count";
        if(!empty(\session('fenbu_id')))
            $where.=" and b.ufenbu_id=".\session('fenbu_id');

        //if($timegap)
        $where.=" and b.ruku_last_time>$this->begin and b.ruku_last_time<$this->end";
        //$where['a.chuku_time']=array(array('gt',$this->begin),array('lt',$this->end));
        if($order_sn)
            $where.=" and b.order_sn like'%".$order_sn."%'";
        if($biaoshi)
            $where.=" and d.biaoshi_xian='".$biaoshi."'";
        if($kehu){
            $where.=" and (b.consignee like'%".$kehu."%' or c.store_name like'%".$kehu."%')";
        }

		$list = M("order b")
		->join('ty_users d on d.user_id=b.user_id')
		->join('ty_store c on b.store_id=c.store_id','LEFT')->order('a.id desc')
		->where($where)
		->order('b.order_id desc')
		->select();

		foreach($list as $key=>$v){
			$list[$key]['order_amount']=$v['order_amount']+$v['yijia_heji'];
		}
                 
    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">商家名</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="160">订单号</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">客户名</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">总件数</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">入库数</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">入库时间</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">金额</td>';
    	$strTable .= '</tr>';
    	
    	foreach($list as $k=>$val){

    		$strTable .= '<tr>';
    		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['store_name'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">&nbsp;'.$val['order_sn'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['consignee'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['jian_count'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['ruku_count'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.date("Y-m-d H:i:s",$val['ruku_last_time']).'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.sanwei($val['order_amount']).'</td>';
    		$strTable .= '</tr>';
    	}
    	$strTable .='</table>';
    	unset($list);
    	downloadExcel($strTable,'PDA入库');
    	exit();
    }
	
    public function export_chuku()
    {
    	//搜索条件
        $order_sn = I('order_sn');
		$kehu = I('kehu');
        $where="b.order_status < 3 and b.shipping_status = 1 and b.jian_count > 0 and b.jian_count = b.chuku_count";
        $where.=" and b.chuku_last_time>$this->begin and b.chuku_last_time<$this->end";
		if($order_sn)
			$where.=" and b.order_sn like'%".$order_sn."%'";
		if($kehu)
			$where.=" and (b.consignee like'%".$kehu."%' or c.store_name like'%".$kehu."%')";
			
			if(!empty(\session('fenbu_id')))
				$where.=" and b.ufenbu_id=".session('fenbu_id');

		$list = M("order b")
            ->field('b.chuku_count,b.chuku_last_time,b.order_id,b.order_sn,b.consignee,b.jian_count,b.order_amount,b.yijia_heji,c.store_name')
            ->join('ty_store c on b.store_id=c.store_id','LEFT')->order('a.id desc')
            ->where($where)
            ->order('b.order_id desc')
            ->select();


		foreach($list as $key=>$v){
			$list[$key]['order_amount']=$v['order_amount']+$v['yijia_heji'];
		}
                 
    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">商家名</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="160">订单号</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">客户名</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">总件数</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">出库数</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">出库时间</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">金额</td>';
    	$strTable .= '</tr>';
    	
    	foreach($list as $k=>$val){

    		$strTable .= '<tr>';
    		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['store_name'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">&nbsp;'.$val['order_sn'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['consignee'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['jian_count'].' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['chuku_count'].'</td>';
    		$strTable .= '<td style="text-align:left;font-size:12px;">'.date("Y-m-d H:i:s",$val['chuku_last_time']).'</td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.sanwei($val['order_amount']).'</td>';
    		$strTable .= '</tr>';
    	}
    	$strTable .='</table>';
    	unset($list);
    	downloadExcel($strTable,'PDA出库');
    	exit();
    }

     public function ruku_pda(){ //入库pda
        $order_sn = I('order_sn');
		$kehu = I('kehu');
		$biaoshi = I('biaoshi');
		$where="b.order_status < 3 and b.shipping_status = 1 and b.jian_count > 0 and b.jian_count = b.ruku_count";
		if(!empty(\session('fenbu_id')))
			$where.=" and b.ufenbu_id=".\session('fenbu_id');
		
        //if($timegap)
			$where.=" and b.ruku_last_time>$this->begin and b.ruku_last_time<$this->end";
			//$where['a.chuku_time']=array(array('gt',$this->begin),array('lt',$this->end));
		if($order_sn)
			$where.=" and b.order_sn like'%".$order_sn."%'";
		if($biaoshi)
			$where.=" and d.biaoshi_xian='".$biaoshi."'";
		if($kehu){
			$where.=" and (b.consignee like'%".$kehu."%' or c.store_name like'%".$kehu."%')";
		}
		
		$count = M("order b")
		->field('b.order_id,b.ruku_last_time,b.order_amount,b.order_id,b.yijia_heji')
		->join('ty_store c on b.store_id=c.store_id')
		->join('ty_users d on b.user_id=d.user_id')
		->where($where)
		->select();

        $Page  = new Page2(count($count),20);
		
		$list = M("order b")
		->field('b.ruku_count,b.ruku_last_time,b.order_id,b.order_sn,b.consignee,b.jian_count,b.order_amount,b.yijia_heji,c.store_name,d.biaoshi_xian')
		->join('ty_store c on b.store_id=c.store_id')
		->join('ty_users d on b.user_id=d.user_id')
		->order('b.order_id desc')
		->where($where)->limit($Page->firstRow.','.$Page->listRows)
		->select();

	    $dprice=0;
		foreach($list as $key=>$v){
			$tuikuan=M('return_goods')->where('order_id='.$v['order_id'])->select(); //退款
			$tuikuans=0;
			foreach($tuikuan as $vs){
				$tuikuans+=sanwei(($vs['member_goods_price']+$vs['yijia'])*$vs['goods_num'])-sanwei(($vs['member_goods_price']+$vs['yijia'])*$vs['goods_num']*$vs['points']/100);
			}
			$list[$key]['tuikuan']=$tuikuans; //退款数
			$list[$key]['order_amount']=$v['order_amount']+$v['yijia_heji'];
			$list[$key]['rukunum']=$v['ruku_count']; //入库标签数
		}

		$tuikuan_hejis=0;
		foreach($count as $vv){
			$dprice+=$vv['order_amount']+$vv['yijia_heji'];
//			$tuikuan_heji=M('return_goods')->where(['order_id'=>$vv['order_id']])->select(); //退款
//            if($tuikuan_heji){
//                foreach($tuikuan_heji as $vs){
//                    $tuikuan_hejis+=sanwei(($vs['member_goods_price']+$vs['yijia'])*$vs['goods_num'])-sanwei(($vs['member_goods_price']+$vs['yijia'])*$vs['goods_num']*$vs['points']/100);
//                }
//            }
		}

		$this->assign('dprice',$dprice);

        $show  = $Page->show();
        $this->assign('show',$show);
		$this->assign('tuikuan_hejis',$tuikuan_hejis);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();
	 }
	 
     public function chuku_pda(){ //出库pda
        $order_sn = I('order_sn');
		$kehu = I('kehu');
         $where="b.order_status < 3 and b.shipping_status = 1 and b.jian_count > 0 and b.jian_count = b.chuku_count";
		if(!empty(\session('fenbu_id')))
			$where.=" and b.ufenbu_id=".\session('fenbu_id');
			
        //if($timegap)
         $where.=" and b.chuku_last_time>$this->begin and b.chuku_last_time<$this->end";
			//$where['a.chuku_time']=array(array('gt',$this->begin),array('lt',$this->end));
		if($order_sn)
			$where.=" and b.order_sn like'%".$order_sn."%'";
		if($kehu)
			$where.=" and (b.consignee like'%".$kehu."%' or c.store_name like'%".$kehu."%')";

		$count = M("order b")
		->field('b.chuku_last_time,b.order_amount,b.order_id,b.yijia_heji')
		->join('ty_store c on b.store_id=c.store_id','LEFT')
		->where($where)
		->select();


        $Page  = new Page2(count($count),20);
		 
		$list = M("order b")
		->field('b.chuku_count,b.chuku_last_time,b.order_id,b.order_sn,b.consignee,b.jian_count,b.order_amount,b.yijia_heji,c.store_name')
		->join('ty_store c on b.store_id=c.store_id','LEFT')->order('a.id desc')
		->where($where)
            ->limit($Page->firstRow.','.$Page->listRows)
            ->order('b.order_id desc')
		->select();

	$dprice=0;
		foreach($list as $key=>$v){
			$list[$key]['order_amount']=$v['order_amount']+$v['yijia_heji'];
			//$list[$key]['chuku_num']+=$v[$this->z.'status_c']; //出库标签数
		}
		
		foreach($count as $v){
			$dprice+=$v['order_amount']+$v['yijia_heji'];
		}
		$this->assign('dprice',$dprice);
		

        $show  = $Page->show();
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();
	 }
	 
	 public function store_jiesuan(){
		$store_id = $_POST['store_id'];
		if($store_id){
			$storeLogic = new StoreLogic();
			$storeLogic->shoudong_transfer($store_id); // 手动结算
			echo '1';
		}
        
	 }
	 
     public function store_duizhang(){
        $store_name = I('store_name');
        $account_bank = I('account_bank');
        $create_time = I('store_time');//echo strtotime(date("Y-m-d"));
		$action=I('action');
			if($action=="jiesuan" && IS_POST){
				$stores=M('store')->where('store_id='.I('store_id'))->find();
					$tuihuo=M('return_goods')->where('store_id='.$stores['store_id'].' and status=1')->select();
					//计算退货钱
					$t_hejiprice=0;
					foreach($tuihuo as $vs){
						$t_hejiprice+=$vs['member_goods_price']*$vs['goods_num']*(100-$vs['points'])/100; //商家应该退回的钱
//                        $payModel = new PayController();
//                        $payModel->returnOrder($vs);
					}

				// 	$stores['yingfu_price']=$stores['store_money'] - $t_hejiprice  - (($stores['store_money'] - $t_hejiprice) * 0.005); //应付+手续费
					$stores['yingfu_price']=$stores['store_money'] - $t_hejiprice  - 0; //应付+手续费
					
				if($stores['store_money']!=0){
					$withdrawals_id=M('store_withdrawals')->add([
						'store_id'=>$stores['store_id'],
						'create_time'=>strtotime(date("Y-m-d",time())),
						'money'=>$stores['store_money'],
						'th_money'=>$t_hejiprice,
				// 		'sxf_money'=>($stores['store_money'] - $t_hejiprice) * 0.005,
						'sxf_money'=>0,
						'yf_money'=>$stores['yingfu_price'],
						'bank_name'=>$stores['bank_name'],
						'account_bank'=>$stores['account_bank'],
						'account_name'=>$stores['account_name'],
						'remark'=>I('remark'),
						'status'=>1,
					]);
					//对应结算记录id
					M('order_statis')->where('store_id='.$stores['store_id'].' and withdrawals_id=0')->save([ 
						'withdrawals_id'=>$withdrawals_id
					]);
					M('return_goods')->where('store_id='.$stores['store_id'].' and status=1')->save([
						'status'=>2,
						'withdrawals_id'=>$withdrawals_id
					]);
					//清零商户余额
					M('store')->where('store_id='.$stores['store_id'])->save([
						'store_money'=>0
					]);
					echo $stores['store_id'];
				}else{
					echo '1';
				}
				
				exit;
			}

        $create_time = str_replace("+"," ",$create_time);
        $create_time2 = $create_time  ? $create_time  : date('Y-m-d 00:00',strtotime('-1 months')).' - '.date('Y-m-d 23:59');
        $create_time3 = explode(' - ',$create_time2);
        //$where['store_time'] =  array(array('gt', strtotime($create_time3[0]), array('lt', strtotime($create_time3[1]))));
        $store_name && $where['store_name'] = array('like','%'.$store_name.'%');
        $account_bank && $where['account_bank'] = array('like','%'.$account_bank.'%');
		if(\session('fenbu_id')!=0){
			$where['a.fenbu_id']=\session('fenbu_id');
		}
// 		$where['a.store_state']=1;
		$where['b.withdrawals_id']=0;
        // dump($where);
        $count = M("order_statis b")
		->field('a.store_id,a.store_money,sum(b.order_totals) as order_amount,sum(b.result_totals) as result_totals')
		->join('ty_store a on b.store_id=a.store_id')
		->group('b.store_id')
		->order('a.dz_sort asc,result_totals desc,a.store_id')
		->where($where) //->where('b.withdrawals_id=0')
		->select();
		//计算合计金额
			$hejiprice=$hejiorderprice=0;
			foreach($count as $v){
				//$order_price=M('order_statis a')->join('ty_order b on a.order_sn=b.order_sn')->where('a.withdrawals_id=0 and a.store_id='.$v['store_id'])->sum('b.order_amount');
				if($v['result_totals']!=$v['store_money'])
					M('store')->where('store_id='.$v['store_id'])->setField(['store_money'=>$v['result_totals']]); 
					
				$tuihuo=M('return_goods')->where('store_id='.$v['store_id'].' and status=1')->select();
				$t_heji_price=0;
				//计算退货钱
				foreach($tuihuo as $vs){
					$t_heji_price+=$vs['member_goods_price']*$vs['goods_num']*(100-$vs['points'])/100; //商家应该退回的钱
				}

				// $hejiprice+=$v['store_money'] - $t_heji_price - (($v['store_money'] - $t_heji_price)* 0.005);
				$hejiprice+=$v['store_money'] - $t_heji_price - 0;
				$hejiorderprice+=$v['order_amount'];
			}

         $Page  = new Page(count($count),10);
		 //$list = M("store a")->order('store_money desc')->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();	//\print_r(\json_encode($list));
		$list = M("order_statis b")
		->field('a.*,sum(b.order_totals) as order_amount,sum(b.result_totals) as result_totals')
		->join('ty_store a on b.store_id=a.store_id')
		->group('b.store_id')
		->where($where)->order('a.dz_sort asc,result_totals desc,a.store_id')->limit($Page->firstRow.','.$Page->listRows)
		->select();
		
		foreach($list as $key=>$v){
			//$order_price=M('order_statis a')->join('ty_order b on a.order_sn=b.order_sn')->where('a.withdrawals_id=0 and a.store_id='.$v['store_id'])->sum('b.order_amount');
			$tuihuo=M('return_goods')->where('store_id='.$v['store_id'].' and status=1')->select();
			//计算退货钱 
			$t_hejiprice=0;
			foreach($tuihuo as $vs){
				$t_hejiprice+=$vs['member_goods_price']*$vs['goods_num']*(100-$vs['points'])/100; //商家应该退回的钱
			}
			$list[$key]['tuihuo_price']=$t_hejiprice;
// 			$list[$key]['yingfu_price']=round($v['store_money'] - (($v['store_money']-$list[$key]['tuihuo_price']) * 0.005) -$t_hejiprice,2); //应付
			$list[$key]['yingfu_price']=round($v['store_money']  -$t_hejiprice,2); //应付
// 			$list[$key]['commission']=($v['store_money']-$list[$key]['tuihuo_price']) * 0.005; //手续费
			$list[$key]['commission']=0; //手续费
			//$list[$key]['listprice']=M('order_statis')->where('withdrawals_id=0 and store_id='.$v['store_id'])->sum('result_totals');
			//M('store')->where('store_id='.$v['store_id'])->setField(['store_money'=>$list[$key]['listprice']]);
		} 
 
        $this->assign('create_time',$create_time2);
        $show  = $Page->show();
		$this->assign('hejiprice',round($hejiprice,2));
		$this->assign('hejiorderprice',sanwei($hejiorderprice));
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();
	 }
	 
    /**
     *  店家转账汇款记录
     */
    public function store_remittance(){
        $model = M("");
        $store_id = I('store_id');
        $account_bank = I('account_bank');
        $account_name = I('account_name');
        
        $create_time = I('create_time');
        $create_time = str_replace("+"," ",$create_time);
        $create_time2 = $create_time  ? $create_time  : date('Y-m-d',strtotime('-1 months')).' - '.date('Y-m-d',strtotime('+1 day'));
        $create_time3 = explode(' - ',$create_time2);
        $where['sr.create_time'] =  array(array('gt', strtotime(strtotime($create_time3[0])), array('lt', strtotime($create_time3[1]))));
        $store_id && $where['s.store_id'] = $store_id;
        $account_bank && $where['sr.account_bank'] = array('like','%'.$account_bank.'%');
        $account_name && $where['sr.account_name'] = array('like','%'.$account_name.'%');
                        
        $count = $model->table(C('DB_PREFIX').'store_remittance sr')->join('INNER JOIN __STORE__ s ON s.store_id = sr.store_id')->where($where)->count();
        $Page  = new Page($count,10);
        $list = $model->table(C('DB_PREFIX').'store_remittance sr')->join('INNER JOIN __STORE__ s ON s.store_id = sr.store_id')->where($where)->order("sr.id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $this->assign('create_time',$create_time2);
        $show  = $Page->show();                 
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();    
    }
    /**
     *  转账汇款记录
     */
    public function remittance(){
        $model = M("");
        $user_id = I('user_id');
        $account_bank = I('account_bank');
        $account_name = I('account_name');
        $create_time = I('create_time');
	if($create_time != ''){
	        $create_time = str_replace("+"," ",$create_time);
	        $create_time2 = $create_time  ? $create_time  : date('Y-m-d',strtotime('-1 months')).' - '.date('Y-m-d',strtotime('+1 day'));
	        $create_time3 = explode(' - ',$create_time2);
	        $where['w.create_time'] =  array(array('gt', strtotime(strtotime($create_time3[0])), array('lt', strtotime($create_time3[1]))));
	}
        $user_id && $where['u.user_id'] = $user_id;
        $account_bank && $where['w.account_bank'] = array('like','%'.$account_bank.'%');
        $account_name && $where['w.account_name'] = array('like','%'.$account_name.'%');
                        
        $count = $model->table(C('DB_PREFIX').'withdrawals w')->join('INNER JOIN __USERS__ u ON u.user_id = w.user_id')->where($where)->count();
        $Page  = new Page($count,16);        
        $list = $model->table(C('DB_PREFIX').'withdrawals w')->join('INNER JOIN __USERS__ u ON u.user_id = w.user_id')->where($where)->order("w.id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('create_time',$create_time2);
        $show  = $Page->show();                 
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();    
    }

    /**
     * 提现申请记录
     */
    public function withdrawals()
    {
        $model = M('');
        $status = I('status');
        $user_id = I('user_id');
        $account_bank = I('account_bank');
        $account_name = I('account_name');
        $create_time = I('create_time');
	if($create_time != ''){
		$create_time = str_replace("+"," ",$create_time);
	        $create_time2 = $create_time  ? $create_time  : date('Y-m-d',strtotime('-1 months')).' - '.date('Y-m-d',strtotime('+1 day'));
	        $create_time3 = explode(' - ',$create_time2);

	        $where['w.create_time'] =  array(array('gt', strtotime(strtotime($create_time3[0])), array('lt', strtotime($create_time3[1]))));
	}
        
        if($status === '0' || $status > 0)
            $where['w.status'] = $status;
        $user_id && $where['u.user_id'] = $user_id;
        $account_bank && $where['w.account_bank'] = array('like','%'.$account_bank.'%');
        $account_name && $where['w.account_name'] = array('like','%'.$account_name.'%');

        $count = $model->table(C('DB_PREFIX').'withdrawals w')->join('INNER JOIN __USERS__ u ON u.user_id = w.user_id')->where($where)->count();
        $Page  = new Page($count,10);
        $list = $model->table(C('DB_PREFIX').'withdrawals w')->join('INNER JOIN __USERS__ u ON u.user_id = w.user_id')->where($where)->order("w.id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('create_time',$create_time2);
        $show  = $Page->show();
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();
    }
    
    /**
     * 删除申请记录
     */
    public function delStoreWithdrawals()
    {
        $model = M("store_withdrawals"); 
        $model->where('id ='.$_GET['id'])->delete(); 
        $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);          
        $this->ajaxReturn(json_encode($return_arr));
    }    
        
    /**
     * 修改编辑商家 申请提现
     */
    public  function editStoreWithdrawals(){        
        $id = I('id');
        $model = M("store_withdrawals");
        $withdrawals = $model->find($id);
        $store = M('store')->where("store_id = {$withdrawals[store_id]}")->find();
        
        if(IS_POST)
        {
                $model->create();
                
                // 如果是已经给店家转账 则生成转账流水记录
                if($model->status == 1 && $withdrawals['status'] != 1)
                {                
                    if($store['store_money'] < $withdrawals['money'])
                    {
                        $this->error("店家余额不足{$withdrawals['money']}，不够提现");    
                        exit;
                    }
                    storeAccountLog($withdrawals['store_id'], ($withdrawals['money'] * -1),0,$desc = '平台提现');
                    $remittance = array(
                        'store_id' => $withdrawals['store_id'],
                        'bank_name' => $withdrawals['bank_name'],
                        'account_bank' => $withdrawals['account_bank'],
                        'account_name' => $withdrawals['account_name'],
                        'money' => $withdrawals['money'],
                        'status' => 1,
                        'create_time' => time(),
                        'admin_id' => session('admin_id'),
                        'withdrawals_id' => $withdrawals['id'],
                        'remark'=>$model->remark,
                    );
                    M('store_remittance')->add($remittance);
                }                
                $model->save();                               
                $this->success("操作成功!",U('store_withdrawals'),3);
                exit;
        }              
       $this->assign('store',$store);
       $this->assign('data',$withdrawals);
       $this->display();           
    }      

    /**
     * 删除申请记录
     */
    public function delWithdrawals()
    {                        
        $model = M("withdrawals"); 
        $result=$model->where('id ='.$_GET['id'])->delete(); 
        if($result){
            $this->success('成功删除');
        }else{
            $this->error('操作失败');
        }
    } 

    /**
     * 删除商家汇款记录
     */
    public function delremittance()
    {                        
        $model = M("store_remittance"); 
        $result=$model->where('id ='.$_GET['id'])->delete(); 
        if($result){
            $this->success('成功删除');
        }else{
            $this->error('操作失败');
        }
    }
	

    
    /**
     * 修改编辑 申请提现
     */
    public  function editWithdrawals(){        
        $id = I('id');
        $model = M("withdrawals");
        $withdrawals = $model->find($id);
        $user = M('users')->where("user_id = {$withdrawals[user_id]}")->find();
        
        if(IS_POST)
        {
                $model->create();
                
                // 如果是已经给用户转账 则生成转账流水记录
                if($model->status == 1 && $withdrawals['status'] != 1)
                {                
                    if($user['user_money'] < $withdrawals['money'])
                    {
                        $this->error("用户余额不足{$withdrawals['money']}，不够提现");    
                        exit;
                    }                                       
                    accountLog($withdrawals['user_id'], ($withdrawals['money'] * -1), 0,"平台提现");
                    $remittance = array(
                        'user_id' => $withdrawals['user_id'],
                        'bank_name' => $withdrawals['bank_name'],
                        'account_bank' => $withdrawals['account_bank'],
                        'account_name' => $withdrawals['account_name'],
                        'money' => $withdrawals['money'],
                        'status' => 1,
                        'create_time' => time(),
                        'admin_id' => session('admin_id'),
                        'withdrawals_id' => $withdrawals['id'],
                        'remark'=>$model->remark,
                    );
                    M('remittance')->add($remittance);
                }                
                $model->save();                               
                $this->success("操作成功!",U('remittance'),3);
                exit;
        }       
       if($user['nickname'])        
           $withdrawals['user_name'] = $user['nickname'];
       elseif($user['email'])        
           $withdrawals['user_name'] = $user['email'];
       elseif($user['mobile'])        
           $withdrawals['user_name'] = $user['mobile'];            
       
       $this->assign('user',$user);
       $this->assign('data',$withdrawals);
       $this->display();           
    }      

    /**
     * 商家提现申请记录
     */
    public function store_withdrawals()
    {
        $model = M("store_withdrawals");
        $store_name = I('store_name');
        $account_bank = I('account_bank');
        $account_name = I('account_name');
        $create_time = I('create_time');

        $create_time = str_replace("+"," ",$create_time);
        $create_time2 = $create_time  ? $create_time  : date('Y-m-d 00:00',strtotime('-1 month')).' - '.date('Y-m-d 23:59',strtotime('+1 day'));
        $create_time3 = explode(' - ',$create_time2);
        //$where['sw.create_time'] =  array(array('egt', strtotime($create_time3[0]), array('lt', strtotime($create_time3[1]))));
		$wheres="sw.create_time>=".strtotime($create_time3[0])." and sw.create_time<".strtotime($create_time3[1]);
        $store_name && $where['s.store_name'] =array('like','%'.$store_name.'%');
        $account_bank && $where['sw.account_bank'] = array('like','%'.$account_bank.'%');
        $account_name && $where['sw.account_name'] = array('like','%'.$account_name.'%');
        if(session('fenbu_id') != 0){
            $where['s.fenbu_id']=\session('fenbu_id');
        }


        $count = $model->table(C('DB_PREFIX').'store_withdrawals sw')->join('INNER JOIN __STORE__ s ON s.store_id = sw.store_id')->where($where)->where($wheres)->select();
		//计算合计金额
			$hejiprice=$heji=$hejisxf=$hejituihuo=0;
			foreach($count as $v){
				$hejiprice+=$v['yf_money'];
                $hejisxf+=$v['sxf_money'];
                $heji+=$v['money'];
                $hejituihuo+=$v['th_money'];
			}
			
        $Page  = new Page(count($count),20);
        $list = $model->table(C('DB_PREFIX').'store_withdrawals sw')->join('INNER JOIN __STORE__ s ON s.store_id = sw.store_id')->where($where)->where($wheres)->order(['s.dz_sort asc','sw.id desc','id desc'])->limit($Page->firstRow.','.$Page->listRows)->select();

        $this->assign('create_time',$create_time2);
        $show  = $Page->show();
		$this->assign('hejiprice',$hejiprice);
		$this->assign('hejisxf',$hejisxf);
		$this->assign('heji',$heji);
		$this->assign('hejituihuo',$hejituihuo);
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();
    }


    public function export_withdrawals()
    {
        $model = M("store_withdrawals");
        $create_time = I('create_time');
        $store_name = I('store_name');
        $account_bank = I('account_bank');
        $account_name = I('account_name');

        $create_time = str_replace("+"," ",$create_time);
        $create_time2 = $create_time  ? $create_time  : date('Y-m-d 00:00',strtotime('-1 month')).' - '.date('Y-m-d 23:59',strtotime('+1 day'));
        $create_time3 = explode(' - ',$create_time2);
        $wheres="sw.create_time>=".strtotime($create_time3[0])." and sw.create_time<".strtotime($create_time3[1]);
        if(session('fenbu_id') != 0){
            $where['s.fenbu_id']=\session('fenbu_id');
        }
        $store_name && $where['s.store_name'] =array('like','%'.$store_name.'%');
        $account_bank && $where['sw.account_bank'] = array('like','%'.$account_bank.'%');
        $account_name && $where['sw.account_name'] = array('like','%'.$account_name.'%');

        $list = $model->table(C('DB_PREFIX').'store_withdrawals sw')->join('INNER JOIN __STORE__ s ON s.store_id = sw.store_id')->where($where)->where($wheres)->order("s.dz_sort asc")->select();


        $strTable ='<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">店铺名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">结算时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">结算金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">退货金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">扣点金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">手续费</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">其他费用</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">应付金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">应补金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">银行名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">银行账号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">开户名</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">备注</td>';
        $strTable .= '</tr>';


        foreach($list as $val){
            
            $koudoan = M('order_statis')->where(['withdrawals_id'=>$val['id']])->sum('commis_totals');
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">'.$val['store_name'].'</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;">'.date('Y-m-d',$val['create_time']).'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['money'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['th_money'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$koudoan.' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['sxf_money'].' </td>';
            
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['expenses'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.round($val['yf_money'],2).' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['repair_money'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">&nbsp;'.$val['bank_name'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">&nbsp;'.$val['account_bank'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">&nbsp;'.$val['account_name'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['remark'].' </td>';
            $strTable .= '</tr>';
        }
        $strTable .='</table>';
        unset($list);
        downloadExcel($strTable,'结算订单记录');
        exit();
    }
    /**
     *  商家结算记录
     */
    public function order_statis(){
        $model = M("order_statis");
        $store_id = I('store_id');
        $create_date = I('create_date');
        $create_date = str_replace("+"," ",$create_date);
        $create_date2 = $create_date  ? $create_date  : date('Y-m-d',strtotime('-1 month')).' - '.date('Y-m-d',strtotime('+1 month'));
        $create_date3 = explode(' - ',$create_date2);
        $where = " create_date >= '".strtotime($create_date3[0])."' and create_date <= '".strtotime($create_date3[1])."' ";
        $store_id && $where .= " and ty_order_statis.store_id = $store_id ";
                        
        $count = $model->where($where)->count();
        $Page  = new Page($count,16);
        $list = $model->join('INNER JOIN __STORE__ ON __STORE__.store_id = __ORDER_STATIS__.store_id')->where($where)->order("`id` desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $this->assign('create_date',$create_date2);
        $show  = $Page->show();                 
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();    
    }
	
    public function order_no_statis()
    {
        $create_date = I('create_date');
        $create_date = str_replace("+"," ",$create_date);
        $create_date2 = $create_date ? $create_date : date('Y-m-d', strtotime('-1 month')) . ' - ' . date('Y-m-d', strtotime('+1 month'));
        $create_date3 = explode(' - ', $create_date2);
        $where = array(
            'pay_status' => 1,
            'add_time' => array(array('gt', strtotime($create_date3[0])), array('lt', strtotime($create_date3[1]))),
			'is_checkout' => 0
        );
        $model = M('order');
        $count = $model->where($where)->count();
        $Page = new Page($count, 16);
        $list = $model->where($where)->order("`add_time` desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();		
		foreach($list as &$v){
			$v['store_name']=M('store')->where('store_id='.$v['store_id'])->getField('store_name');
		}
        $this->assign('create_date', $create_date2);
        $show = $Page->show();
        $order_status = C('ORDER_STATUS');
        $shipping_status = C('SHIPPING_STATUS');
        $this->assign('shipping_status',$shipping_status);
        $this->assign('order_status',$order_status);
        $this->assign('show', $show);
        $this->assign('list', $list);
        C('TOKEN_ON', false);
        $this->display();
    }
	
    /**
     * 删除商家结算记录
     */
    public function delorderstatis()
    { 
        $model = M("order_statis"); 
        $result=$model->where('id ='.$_GET['id'])->delete(); 
        if($result){
            $this->success('成功删除');
        }else{
            $this->error('操作失败');
        }
    }
	
    public function order_statis_shouhuo()
    {
		$id= I('id');
		$store_id=I('store_id');
		$order_sn= I('order_sn');
        $model = M("order_statis a");
        $where = "a.store_id = ".$store_id." and a.withdrawals_id=".$id;
		if($order_sn){
			$where .= " and a.order_sn like '%".$order_sn."%'";
		}

        $count = $model
		->field('a.*,b.add_time')
		->join('ty_order b on a.order_sn=b.order_sn','LEFT')
		->where($where)->select();
		//计算合计金额
			$dan_heji=$kou_heji=$yin_heji=0;
			foreach($count as $v){
				$dan_heji+=$v['order_totals'];
				$kou_heji+=$v['commis_totals'];
				$yin_heji+=$v['result_totals'];
			}
			
        $Page  = new Page(count($count),20);
        $list = $model
        ->field('a.*,b.order_id,d.company')
        ->join('ty_order b on a.order_sn=b.order_sn','LEFT')
        ->join('ty_users d on b.user_id=d.user_id')
        ->where($where)->order("a.create_date asc")
        ->limit($Page->firstRow.','.$Page->listRows)->select();
        
        foreach($list as $key=>$v){
        	$list[$key]['ruku_time']=M('order_jian')->where('order_id='.$v['order_id'])->getField('ruku_time');
        }
        
        $this->assign('create_date',$create_date2);
        $show  = $Page->show();
		$this->assign([
			'dan_heji'=>$dan_heji,
			'kou_heji'=>$kou_heji,
			'yin_heji'=>$yin_heji
		]);
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();
	}

    public function order_statis_tuihuo()
    {
		$id= I('id');
		$store_id=I('store_id');
		$goods_name= I('goods_name');
        $where = "a.store_id = ".$store_id." and a.withdrawals_id=".$id;
		if($goods_name){
			$where .= " and a.remark like '%".$goods_name."%'";
		}

        $count =M("return_goods a") 
		->field('a.*,b.*,c.goods_name,c.original_img')
		->join('ty_users b ON a.user_id = b.user_id','LEFT')
		->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
		->where($where)->select();
		//计算合计金额
			$dsprice=$kou_heji=$yin_heji=$dan_heji=0;
			foreach($count as $v){
				$dsprice=(float)$v['member_goods_price']*(float)$v['goods_num']; //订单价
				$dan_heji+=$dsprice;
				$kou_heji+=$dsprice*($v['points']/100); //平台价
				$yin_heji+=$dsprice-($dsprice*($v['points']/100));
			}
			
        $Page  = new Page(count($count),20);
        $list =M("return_goods a") 
		->field('a.*,b.*,c.goods_name,c.original_img')
		->join('ty_users b ON a.user_id = b.user_id','LEFT')
		->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
		->where($where)->order("`id` desc")->limit($Page->firstRow.','.$Page->listRows)->select();
		
		foreach($list as $key=>$v){
			$list[$key]['dsprice']=(float)$v['member_goods_price']*(float)$v['goods_num']; //订单价
			$list[$key]['ptprice']=$list[$key]['dsprice']*($v['points']/100); //平台价
			$list[$key]['ptprices']=$list[$key]['dsprice']-$list[$key]['ptprice'];
			// $heji_ptprice+=$ptprice;
			// $heji_ptprices+=$ptprices;
		}
        
        $this->assign('create_date',$create_date2);
        $show  = $Page->show();
		$this->assign([
			'dan_heji'=>$dan_heji,
			'kou_heji'=>$kou_heji,
			'yin_heji'=>$yin_heji
		]);
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        $this->display();
	}


    public function pda_qr_show()
    {
        $pda_qr_id = session('pda_qr_id');
        if(!$pda_qr_id){
            $this->error('请登录',U('/Admin/Finance/pda_qr_login'));
        }
        $this->display();
    }

    public function pda_qr_login()
    {
        if(IS_POST){
            $password = I('password');
            if($password == 1008611){
                session('pda_qr_id',1);
                $this->success('登录成功',U('/Admin/Finance/pda_qr_show'));
            }else{
                $this->error('密码错误',U('/Admin/Finance/pda_qr_login'));
            }
        }
        $this->display();
    }
    public function export_statis_shouhuo()
    {
    	//搜索条件
		$id= I('id');
		$order_sn= I('order_sn');
		$store_id= I('store_id');
        $model = M("order_statis a");
        $where = "a.store_id = ".$store_id." and a.withdrawals_id=".$id;
		if($order_sn){
			$where .= " and a.order_sn like '%".$order_sn."%'";
		}

        $orderList = $model
		->field('a.*,b.order_id')
		->join('ty_order b on a.order_sn=b.order_sn','LEFT')
		->where($where)->order('a.id desc')->select();
		//echo \json_encode($condition);exit;
		foreach($orderList as $key=>$v){
			$orderList[$key]['ruku_time']=M('order_jian')->where('order_id='.$v['order_id'])->getField('ruku_time');
		}
		
    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">单号</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单金额</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台扣点</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">应收金额</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">入库时间</td>';
    	$strTable .= '</tr>';
    	

    	foreach($orderList as $val){
    		$strTable .= '<tr>';
    		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_sn'].'</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['order_totals'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['commis_totals'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['result_totals'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.\date('Y-m-d H:i',$val['ruku_time']).'</td>';
    		$strTable .= '</tr>';
    	}
    	$strTable .='</table>';
    	unset($orderList);
    	downloadExcel($strTable,'结算订单');
    	exit();
    }
	
    public function export_statis_tuihuo()
    {
    	//搜索条件
		$id= I('id');
		$goods_name= I('goods_name');
		$store_id= I('store_id');
        $where = "a.store_id = ".$store_id." and a.withdrawals_id=".$id;
		if($goods_name){
			$where .= " and a.remark like '%".$goods_name."%'";
		}

        $orderList =M("return_goods a") 
		->field('a.*,b.*,c.goods_name,c.original_img')
		->join('ty_users b ON a.user_id = b.user_id','LEFT')
		->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
		->where($where)->order('a.id desc')->select();
		foreach($orderList as $key=>$v){
			$orderList[$key]['dsprice']=(float)$v['member_goods_price']*(float)$v['goods_num']; //订单价
			$orderList[$key]['ptprice']=$orderList[$key]['dsprice']*($v['points']/100); //平台价
			$orderList[$key]['ptprices']=$orderList[$key]['dsprice']-$orderList[$key]['ptprice'];
			// $heji_ptprice+=$ptprice;
			// $heji_ptprices+=$ptprices;
		}
		//echo \json_encode($condition);exit;
		
    	$strTable ='<table width="500" border="1">';
    	$strTable .= '<tr>';
    	$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">单号/备注</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">买家</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">产品</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">单价</td>';
    	$strTable .= '<td style="text-align:center;font-size:12px;" width="*">数量</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单价</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">平台扣点</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">应扣金额</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">退货时间</td>';
    	$strTable .= '</tr>';
    	

    	foreach($orderList as $val){
    		$strTable .= '<tr>';
    		$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['remark'].'</td>';
			$strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['company'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_name'].'</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['member_goods_price'].' </td>';
			$strTable .= '<td style="text-align:left;font-size:12px;">'.$val['goods_num'].' </td>';
			$strTable .= '<td style="text-align:left;font-size:12px;color:#f39c12;">'.$val['dsprice'].' </td>';
			$strTable .= '<td style="text-align:left;font-size:12px;color: blue;">'.$val['ptprice'].' </td>';
			$strTable .= '<td style="text-align:left;font-size:12px;color:red;">'.$val['ptprices'].' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">'.\date('Y-m-d H:i',$val['addtime']).'</td>';
    		$strTable .= '</tr>';
    	}
    	$strTable .='</table>';
    	unset($orderList);
    	downloadExcel($strTable,'结算退货订单');
    	exit();
    }
    
    
    /*
    *新确认收款
    */
    public function pda_piliang2(){
        $datas=I('datas');
        $datas=\explode(',',$datas);
			$myorders='';
			foreach($datas as $v){
				$os=\explode('|',$v);
				$order_id=$os[0];
				$store_id=$os[1];
				// dump($order_id);
				$orderInfo = M('order')->where(['order_id'=>$order_id])->find();
				if($orderInfo['order_status_title'] == 1){
				    M('order')->where(['order_id'=>$order_id])->save(['order_status_title'=>2]);
				    M('users_price')->where('order_id='.$order_id)->setField(['status'=>2]);
				}
				
			}
        
        $json_arr = [];
        $json_arr['code'] = 1;
        $json_str = json_encode($json_arr);
    	exit($json_str);
    }


    /*
*新确认收款
*/
    public function pda_master_piliang2(){
        $datas=I('datas');
        $datas=\explode(',',$datas);
        $myorders='';
        foreach($datas as $v){
            $order_ids = M('order')->where(['master_order_sn'=>$v])->getField('order_id,store_id');
            foreach ($order_ids as $key=>$item){
                $order_id=$key;
                $orderInfo = M('order')->where(['order_id'=>$order_id])->find();
                if($orderInfo['order_status_title'] == 1){
                    M('order')->where(['order_id'=>$order_id])->save(['order_status_title'=>2]);
                }
            }


        }

        $json_arr = [];
        $json_arr['code'] = 1;
        $json_str = json_encode($json_arr);
        exit($json_str);
    }


    /*
        * 临时自动收款
        * */
    public function ordersettlement(){
//        $stareTime  = 1702742400; //2023-11-13 00:00:00
//        $endTime    = 1703433599; //2023-11-14 23:59:59

        if(IS_POST){
            $create_time = I('create_time');
            $stareTime  = strtotime($create_time); //2023-11-13 00:00:00
            $endTime    = $stareTime+86399; //2023-11-14 23:59:59
            
            $orderList = M('order')->field('order_id,store_id')
                ->where('chuku_last_time >'.$stareTime.' and chuku_last_time<'.$endTime.' and is_checkout = 0 and order_status < 3 and shipping_status = 1 and pda_qdzt = 0 and ruku_count > 0 and chuku_count > 0 and chuku_count = ruku_count and ruku_count = jian_count and driver_id > 0 and pda_checkout = 0 and is_checkout = 0')
                ->select();

            // $count = M('order a')
            // ->field('a.user_id,SUM(a.total_amount+yijia_heji) as total_amount,SUM(order_amount+yijia_heji) as order_amount,SUM(coupon_price) as coupon_price')
            // ->join('ty_users c on a.user_id=c.user_id','LEFT')
            // ->join('ty_store d on a.store_id=d.store_id','LEFT')
            // ->join('ty_users e on a.driver_id=e.user_id','LEFT')
            // ->where($condition)->order('a.order_id desc')->group('a.user_id')
            // ->select();
        // dump($orderList);
        //     die;
            foreach($orderList as $k=>$vs){
                //更新产品销量
                $order_list=M("order_goods")->field('goods_id,goods_num')->where('order_id='.$vs['order_id'])->select();
                foreach($order_list as $v){
                    M('goods')->where('goods_id='.$v['goods_id'])->setInc('sales_sum',(int)$v['goods_num']);
                }
                M("order")->where('order_id='.$vs['order_id'])->save([
                    'order_status'=>'2',
                    'pay_status'=>'1',
                    'pda_checkout'=>'1'
                ]);
                //溢价状态
                M("order_yijia")->where('order_id='.$vs['order_id'])->setField('yijia_status','1');


                //开始结算
                $list = M('order')->where('order_id='.$vs['order_id'].' and is_checkout=0 and order_status in(2,4)')->find();

                if(empty($list)) // 没有数据直接跳出
                    return false;

                $data = array(
                    'start_date' => time(), // 结算时间
                    'end_date'   => time(), // 结算截止时间
                    'create_date'=>  time(), // 记录创建时间
                    'store_id'   => $vs['store_id'], // 店铺id
                );

                $order_goods = M('order_goods')->where(array('order_id' => $vs['order_id']))->select();//订单商品列表
                $commis_totals=0;

                if($list['dai_type']==2){
                    $commis_totals=$number=$list['order_amount']*$order_goods[0]['points']/100;
                    //$number *= -1;
                }else{
                    foreach($order_goods as $vss){
                        $commis_totals+=$vss['points']*$vss['member_goods_price']*$vss['goods_num']/100;
                    }
                }
                if($list['shi_price']>0)
                    $list['order_amount']=$list['shi_price'];

                $data['result_totals'] =$list['order_amount']-sanwei($commis_totals); //+$list['integral_money'];// 本期应结

                $data['order_sn'] = $list['order_sn'];// 订单商品金额
                $data['order_totals'] =$list['total_amount'];// 订单商品金额
                $data['shipping_totals'] = $list['shipping_price'];// 运费
                $data['commis_totals'] =  \sanwei($commis_totals);// 平台费用
                $data['discount_totals'] =  $list['discount'];// 改单价

                M('order')->where("order_id =".$list['order_id'])->save(array('is_checkout' =>1,'order_status_title'=>1)); // 标识为已经结算
                M('order_statis')->add($data); // 添加一笔结算统计

                // 给商家加钱 记录日志
                storeAccountLog($vs['store_id'],$data['result_totals'],$data['result_totals'] * -1,'平台订单结算');
                //开始计算积分
                accountLog($list['user_id'],0,$list['order_amount'],'订单 '.$list['order_sn'].' 赠送的积分！',0,$list['order_id']);

            }
           $this->success('操作成功',U('Admin/Finance/ordersettlement',['create_time'=>$create_time]));
           exit;
        }

        $this->display();
    }
    
    public function moling(){
        $condition = array();
        I('kehu') ? $condition['c.company'] = array('like','%'.trim(I('kehu')).'%') : false;
        I('shanghu') ? $condition['d.store_name'] = array('like','%'.trim(I('shanghu')).'%') : false;
        $action=$_POST['action'];$order_ids=$_POST['datas'];$str=$_POST['str'];
        $shoukuan=I('shoukuan');
        $order1 = 'c.xsort asc';
        $order2 = 'a.order_id desc';

        if(I('order_sn') ){
            $subQuery_orderIds = M()->query('select order_id from ty_order WHERE LOCATE('.I('order_sn').',order_sn) > 0');
            foreach ($subQuery_orderIds as $item){
                $ids[] = $item['order_id'];
            }
            if($ids){
                $condition['a.order_id'] = ['in',join(',',$ids)];
            }else{
                $condition['a.order_id'] = 0;
            }
        }
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        I('biaoshi_xian') && $condition['c.biaoshi_xian'] = I('biaoshi_xian');
        I('moling') && $condition['a.change'] = I('biaoshi_xian');
   
        $condition['a.change'] = ['gt',0];
     
        $order_status_title = I('order_status_title');
        
            if($order_status_title == 1 ){
                $condition['a.order_status_title'] = 0;
                // $myw .= ' and a.order_status_title = 0';
            }elseif($order_status_title == 2 ){
                $condition['a.order_status_title'] = 1;
                // $myw .= ' and a.order_status_title = 1';
            }elseif($order_status_title == 3 ){
                $condition['a.order_status_title'] = 2;
                // $myw .= ' and a.order_status_title = 2';
            }
      

        $condition['a.order_status'] = ['in','0,1,2'];//判断要列出的订单状态
        // $myw .= ' and a.order_status in (0,1,2)';
        // $condition['_string'] = '(a.ruku_count = a.jian_count and a.chuku_count = a.ruku_count and a.ruku_last_time is not null and a.chuku_last_time is not null and a.driver_id > 0)';


        if($shoukuan!=""){
            $condition['a.pda_checkout'] = $shoukuan;
            $condition['a.is_checkout'] = $shoukuan;
            // $myw.=' and a.pda_checkout = "'.$shoukuan.'" ';
            // $myw.=' and a.is_checkout = "'.$shoukuan.'" ';
        }

        if(I('duizhang_sn')){
            $orderIds = M('pda_duizhang')->where(['duizhang_sn'=>I('duizhang_sn')])->getField('order_ids');
            if($orderIds){
                $orderIds = json_decode($orderIds,true);
                $condition['a.order_id'] = ['in',join(',',$orderIds)];
                // $myw.=' and a.order_id in ('.join(',',$orderIds).') ';
                $order1 = 'field(a.order_id,'.join(',',$orderIds).')';
                $order2 = 'field(a.order_id,'.join(',',$orderIds).')';
            }

        }else{
            if($this->begin && $this->end){
                $condition['a.add_time'] = array('between',"$this->begin,$this->end");
                // $myw.=' and a.add_time > "'.$this->begin.' " and  a.add_time < "'.$this->end.'" ' ;
            }
        }

        if(I('tag')){
            if(I('tag') == 1){
                $condition['a.tag_price'] = ['eq',0];
                // $myw.=" AND a.tag_price = 0 ";
            }else{
                $condition['a.tag_price'] = ['neq',0];
                // $myw.=" AND a.tag_price <> 0 ";
            }
        }


        $count = M('order a')
            ->field('a.change,a.total_amount')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->where($condition)->order($order1)->group('a.order_id')
            ->select();
        $change = $heji_price = 0;
        foreach ($count as $item){
            $change += $item['change'];
            $heji_price += $item['total_amount'];
        }
        $order_count = count($count);

        // dump($condition);

        $Page  = new Page2(count($count), $_GET['num']);

        //获取订单列表
        $orderList = M('order a')
            ->field('a.add_time,a.change_time,a.change,a.ruku_last_time,a.chuku_last_time,a.order_id,a.order_sn,a.store_id,a.jian_count,a.order_amount,a.tag_price,c.nickname,c.company,d.store_name,c.biaoshi_xian,a.ruku_count,a.chuku_count,a.is_checkout,a.admin_note,a.yijia_heji,a.coupon_price,a.total_amount,a.order_status_title')
//             ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->where($condition)
            ->limit("$Page->firstRow,$Page->listRows ")
            ->order($order1)
            ->group('a.order_id')->select(); //过滤获取主订单

        // foreach($orderList as $v){
        // 	$user_ids.=$v['user_id'].',';
        // }
        // $user_ids=\rtrim($user_ids,',');
        $order_status_title = I('order_status_title');
        $wheress = '';
        if(!empty($order_status_title)){
            $wheress = 'and a.order_status_title = '.$order_status_title;
        }
        $order_sn = I('order_sn');
        $changes = $heji_prices = 0;
        foreach($orderList as $key=>$v) { //整理子单

            if($v['change_time']){
                $orderList[$key]['change_time'] = date('Y-m-d H:i:s',$v['change_time']);
            }
            $orderList[$key]["xiaoji"] = $xiaoji;
            $orderList[$key]["order_list"] = $order_list;
            $changes += $v['change'];
            $heji_prices += $v['total_amount'];
        }
        // dump($orderList);
        //echo json_encode($orderList);
        $store_list = M('store')->getField('store_id,store_name');
        $this->assign('store_list',$store_list);
        $this->assign('show',$Page->show());
        $this->assign('list',$orderList);
        $this->assign('heji_price',geshi($heji_price));
        $this->assign('change',$change);
        $this->assign('heji_prices',geshi($heji_prices));
        $this->assign('changes',$changes);
        C('TOKEN_ON',false);
        $this->display();
    }
    
    public function export_moling(){
        
        $condition = array();
        I('kehu') ? $condition['c.company'] = array('like','%'.trim(I('kehu')).'%') : false;
        I('shanghu') ? $condition['d.store_name'] = array('like','%'.trim(I('shanghu')).'%') : false;
        $action=$_POST['action'];$order_ids=$_POST['datas'];$str=$_POST['str'];
        $shoukuan=I('shoukuan');
        $order1 = 'c.xsort asc';
        $order2 = 'a.order_id desc';

        if(I('order_sn') ){
            $subQuery_orderIds = M()->query('select order_id from ty_order WHERE LOCATE('.I('order_sn').',order_sn) > 0');
            foreach ($subQuery_orderIds as $item){
                $ids[] = $item['order_id'];
            }
            if($ids){
                $condition['a.order_id'] = ['in',join(',',$ids)];
            }else{
                $condition['a.order_id'] = 0;
            }
        }
        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $condition['user_id'] = trim(I('user_id')) : false;
        I('biaoshi_xian') && $condition['c.biaoshi_xian'] = I('biaoshi_xian');
        I('moling') && $condition['a.change'] = I('biaoshi_xian');
   
        $condition['a.change'] = ['gt',0];
     
        $order_status_title = I('order_status_title');
        
            if($order_status_title == 1 ){
                $condition['a.order_status_title'] = 0;
                // $myw .= ' and a.order_status_title = 0';
            }elseif($order_status_title == 2 ){
                $condition['a.order_status_title'] = 1;
                // $myw .= ' and a.order_status_title = 1';
            }elseif($order_status_title == 3 ){
                $condition['a.order_status_title'] = 2;
                // $myw .= ' and a.order_status_title = 2';
            }
      

        $condition['a.order_status'] = ['in','0,1,2'];//判断要列出的订单状态
        // $myw .= ' and a.order_status in (0,1,2)';
        // $condition['_string'] = '(a.ruku_count = a.jian_count and a.chuku_count = a.ruku_count and a.ruku_last_time is not null and a.chuku_last_time is not null and a.driver_id > 0)';


        // if($shoukuan!=""){
        //     $condition['a.pda_checkout'] = $shoukuan;
        //     $condition['a.is_checkout'] = $shoukuan;
        //     // $myw.=' and a.pda_checkout = "'.$shoukuan.'" ';
        //     // $myw.=' and a.is_checkout = "'.$shoukuan.'" ';
        // }

        if(I('duizhang_sn')){
            $orderIds = M('pda_duizhang')->where(['duizhang_sn'=>I('duizhang_sn')])->getField('order_ids');
            if($orderIds){
                $orderIds = json_decode($orderIds,true);
                $condition['a.order_id'] = ['in',join(',',$orderIds)];
                // $myw.=' and a.order_id in ('.join(',',$orderIds).') ';
                $order1 = 'field(a.order_id,'.join(',',$orderIds).')';
                $order2 = 'field(a.order_id,'.join(',',$orderIds).')';
            }

        }else{
            if($this->begin && $this->end){
                $condition['a.add_time'] = array('between',"$this->begin,$this->end");
                // $myw.=' and a.add_time > "'.$this->begin.' " and  a.add_time < "'.$this->end.'" ' ;
            }
        }

        // if(I('tag')){
        //     if(I('tag') == 1){
        //         $condition['a.tag_price'] = ['eq',0];
        //         // $myw.=" AND a.tag_price = 0 ";
        //     }else{
        //         $condition['a.tag_price'] = ['neq',0];
        //         // $myw.=" AND a.tag_price <> 0 ";
        //     }
        // }


 

       


        //获取订单列表
        $datas = M('order a')
            ->field('a.add_time,a.change_time,a.change,a.ruku_last_time,a.chuku_last_time,a.order_id,a.order_sn,a.store_id,a.jian_count,a.order_amount,a.tag_price,c.nickname,c.company,d.store_name,c.biaoshi_xian,a.ruku_count,a.chuku_count,a.is_checkout,a.admin_note,a.yijia_heji,a.coupon_price,a.total_amount,a.order_status_title')
//             ->join('ty_order_jian b on a.order_id=b.order_id','LEFT')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->where($condition)
            ->order($order1)
            ->group('a.order_id')->select(); //过滤获取主订单

        // foreach($orderList as $v){
        // 	$user_ids.=$v['user_id'].',';
        // }
        // $user_ids=\rtrim($user_ids,',');
        $order_status_title = I('order_status_title');
        $wheress = '';
        if(!empty($order_status_title)){
            $wheress = 'and a.order_status_title = '.$order_status_title;
        }
       
        
        $e_name='联鑫壹天达五金商城';
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Worksheet.Drawing");
        import("Org.Util.PHPExcel.Writer.Excel2007");
        $objPHPExcel = new \PHPExcel();
        $objActSheet = $objPHPExcel->getActiveSheet();

        $objActSheet->setCellValue('A1', '订单号');
        $objActSheet->setCellValue('B1', '商户名');
        $objActSheet->setCellValue('C1', '客户名');
        $objActSheet->setCellValue('D1', '线路');
        $objActSheet->setCellValue('E1', '订单价');
        $objActSheet->setCellValue('F1', '抹零金额');
        $objActSheet->setCellValue('G1', '添加时间');
        $objActSheet->setCellValue('H1', '抹零时间');

        $objActSheet->getDefaultRowDimension()->setRowHeight(25);
        $objActSheet->getDefaultColumnDimension()->setWidth(25);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);


        $i=2;
     

        foreach($datas as $v){
            if($v['change_time']){
                $v['change_time'] = date('Y-m-d H:i:s',$v['change_time']);
            }
            $objActSheet->setCellValue('A'.$i, ' '.$v['order_sn']);
            $objActSheet->setCellValue('B'.$i, $v['store_name']);
            $objActSheet->setCellValue('C'.$i, ' '.$v['company']);
            $objActSheet->setCellValue('D'.$i, $v['biaoshi_xian']);
            $objActSheet->setCellValue('E'.$i, $v['order_amount']);
            $objActSheet->setCellValue('F'.$i, $v['change']);
            $objActSheet->setCellValue('G'.$i, date('Y-m-d H:i:s',$v['add_time']));
            $objActSheet->setCellValue('H'.$i, $v['change_time']);
            $i++;
        }

        // 设置单元格边框
        $styleThinBlackBorderOutline = array(
            'borders' => array(
                'allborders' => array( //设置全部边框
                    'style' => \PHPExcel_Style_Border::BORDER_THIN //粗的是thick
                ),

            ),
        );

        $objPHPExcel->getActiveSheet()->getStyle( 'A1:H'.($i-1))->applyFromArray($styleThinBlackBorderOutline);

//         if($i < 1000000){
//             $num2 = 0;
//             foreach (array_values($orderList) as $k=>$v) {
//                 if ($k == 0) {
//                     $num1 = 2;
//                     $num2 = $num1+count($v)-1;
//                 }else {
//                     $num1 = $num2+1;
//                     $num2 = $num1+count($v)-1;
//                 }

//                 $objActSheet->mergeCells('A'.$num1.':A'.$num2);//合并单元格
// //            $objActSheet->mergeCells('B'.$num1.':B'.$num2);//合并单元格
//                 $objActSheet->mergeCells('H'.$num1.':H'.$num2);//合并单元格
//             }
//         }


            ob_end_clean();
            $fileName = $e_name.'对账单';
            $date = date("Y-m-d",time());
            $fileName .= "_{$date}.xlsx";
            //重命名表
            $objPHPExcel->getActiveSheet()->setTitle('viateams');
            //设置活动单指数到第一个表,所以Excel打开这是第一个表
            $objPHPExcel->setActiveSheetIndex(0);
            header('Content-Type: application/vnd.ms-excel');
            header("Content-Disposition: attachment;filename=\"$fileName\"");
            header('Cache-Control: max-age=0');
            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');


            ob_start();
            $objWriter->save("php://output");
            $xlsdata = ob_get_contents();
            ob_end_clean();
            $data=['filename' => $fileName, 'file' => "data:application/vnd.ms-excel;base64," . base64_encode($xlsdata)];
            echo json_encode($data);
            exit;
    }
    
 
}